Monday, April 07, 2008 10:40 PM
I'm with the folloiwng error:
CallbackOnCollectedDelegate was detected
A callback was made on a garbage collected delegate of type 'blocksite!blocksite.DDEClient+DdeCallbackHandler::Invoke'. This may cause application crashes, corruption and data loss. When passing delegates to unmanaged code, they must be kept alive by the managed application until it is guaranteed that they will never be called.
Can someone know how to fix or avoid it?
Thursday, April 10, 2008 5:35 AMModeratorHi Kassiano,
You need to extend your delegate variable's lifetime. Declare it in your Class definition level. Don't declare it in the function or subroutine in this scenario. The following text comes from this blog.
Commonly GC will collect some object which isn't referenced by your code. When you call some unmanaged code, you use a managed delegate as the callback function. It is marshaled to unmanaged code, where they are exposed as unmanaged function pointers. Calls on those pointers will perform an unmanaged to managed transition; a change in calling convention; entry into the correct AppDomain; and any necessary argument marshaling. Clearly the unmanaged function pointer must refer to a fixed address. It would be a disaster if the GC were relocating that! This leads many applications to create a pinning handle for the delegate. This is completely unnecessary. The unmanaged function pointer actually refers to a native code stub that we dynamically generate to perform the transition & marshaling. This stub exists in fixed memory outside of the GC heap.
However, the application is responsible for somehow extending the lifetime of the delegate until no more calls will occur from unmanaged code. The lifetime of the native code stub is directly related to the lifetime of the delegate. Once the delegate is collected, subsequent calls via the unmanaged function pointer will crash or otherwise corrupt the process. In our recent release, we added a Customer Debug Probe which allows you to cleanly detect this – all too common – bug in your code. If you haven’t started using Customer Debug Probes during development, please take a look!