If the unmanaged code needs to call the callback in the managed code multiple times, save the reference of the delegate as a member variable. Otherwise, an exception similar to the following occurs:
CallbackOnCollectedDelegate Detected
Message: For "Demo! SomeNamespace. SomeClass + SomeDelegate: Invoke "type of garbage collection delegate for callback. This may cause application crash, damage, and data loss. When delivering delegates to unmanaged code, managed applications must keep these delegates active until you are sure they will not be called again.
If the new delegate is referenced with a local variable instead of a member variable, the initial callback of the unmanaged code may be OK, however, the exception mentioned above will occur next, because GC destroys the local variables and the delegate objects referenced by the local variables, when the unmanaged code accesses the function pointer again, the address pointed to by the pointer is invalid.