I think something wrong will happen (but not usually) when you just save the delegate object. As we all know, managed memory will be organized by the Garbage Collect. (This means that the physical memory address of the managed entity will be changed.)
Imaging there is a delegate with a long service life, which is called using its own code, we set the delegate as a static member or a member of the class. But sometimes (we donβt know when, we just know that this will happen), the GC organized the memory, and the physical memory of the delegate can be from 0x000000A to 0x0000010. But the native code does not know anything about this, for its own code, it only knows to call 0x000000A forever. Therefore, we must not only store the delegate object, but also use GCHandle.Alloc to tell the GC not to move the physical memory of the delegate object. Then the native code will work well during the callback.
Good, because the GC does not arrange managed memory often, so for a delegate with a short lifetime, even you do not call GCHandle.Alloc, your codes are always "DO WELL", but sometimes it will be crazy. Now you know the reason.
link: http://dotnet.dzone.com/news/net-memory-control-use-gchandl
source share