Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is await forbidden in unsafe sections?

According to http://blogs.msdn.com/b/pfxteam/archive/2012/04/12/async-await-faq.aspx, the await keyword is forbidden inside an unsafe block, mentioning only 'difficulties inherent to preserving unmanaged pointers.' Is there a good explanation available on what those difficulties are?

like image 925
Sebastian Good Avatar asked Mar 03 '13 03:03

Sebastian Good


1 Answers

Two basic things you need to know. An async method gets rewritten by the C# compiler into a little class with an unspeakable name that wraps a state machine. The local variables of the async method become fields of that class.

Unsafe code quite often relies on being able to create pointers to local variables. The fixed statement is like that, it creates a hidden local variable that the garbage collector can see and thus update when a garbage collection occurs that moves the array that is being fixed. Creating pointers to local variables is fine, those variables are not subject to being ever moved by the garbage collector. The stack of a thread is always in a fixed location in the virtual memory address space.

Connect the two and you see the problem, a local variable can turn into a field of a class, a field whose address does change when a garbage collection occurs. Suddenly turning unsafe code into breaking code.

A code snippet that demonstrates the issue:

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

The C# team could have made the effort to carefully analyze the cases where unsafe code is still okay after rewriting. But some cases are just not fixable, like the fixed statement. A bunch of work to only give disappointing news to the programmer, often for a bewildering reason. The sane thing to do here was to simply declare unsafe code off limits.

like image 132
Hans Passant Avatar answered Oct 03 '22 18:10

Hans Passant