Prevent delegate from being garbage collected

老子叫甜甜 提交于 2019-12-05 18:44:14
Hans Passant

You are missing the effect that using a debugger has on the lifetime of local variables. With a debugger attached, the jitter marks the variables in use until the end of the method. Important to make debugging reliable. This however also prevents the GC.Collect() call from collecting the delegate object.

This code will crash when you run the Release build of your program without a debugger.

An in-depth answer on the affect of Debug build behavior on the garbage collector is available in this post

The 'Alloc' call adds a reference to the delegate, which prevents the GC from collecting it. You have to keep the handle returned from Alloc and call Free() on it when you are done using the function pointer. The delegate will be GC'ed without the call to Alloc. If you don't call Free() on the GCHandle, the program will leak. The memory environment is a bit different when running in the debugger. Make sense?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!