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;
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.
Hans passant
source share