Why is it forbidden to wait in prohibited sections?

According to http://blogs.msdn.com/b/pfxteam/archive/2012/04/12/async-await-faq.aspx the await keyword is not allowed inside the unsafe block, pointing only to the "difficulties inherent in saving unmanaged pointers " Are there any good explanations regarding these difficulties?

+7
source share
1 answer

Two main things you need to know. The asynchronous method is rewritten by the C # compiler into a small class with an inexpressible name that wraps the state machine. The local variables of the async method become the fields of this class.

Insecure code often relies on the ability to create pointers to local variables. A fixed statement is similar to this, it creates a hidden local variable that the garbage collector can see and, therefore, update when garbage collection occurs that moves the fixed array. Creating pointers to local variables is fine; these variables cannot be moved by the garbage collector. The thread stack is always in a fixed location in the address space of virtual memory.

Connect two, and you will see a problem, a local variable can turn into a class field, a field whose address changes when garbage collection occurs. Suddenly turn unsafe code into code break.

A snippet of code that demonstrates the problem:

 class Example { int field; unsafe void Method() { int local = 42; int* p = &local; // fine int* q = &field; // CS0212 } } 

The C # team could make an effort to carefully analyze cases where unsafe code is still valid after being rewritten. But some cases are simply not fixed, like a fixed operator. A lot of work that only gives disappointing news to the programmer, often for bewilderment. Common sense here was simply to declare unsafe code outside of the bounds.

+7
source

All Articles