在.NET中,在此代码之后,什么机制阻止Thread对象被垃圾回收?
new Thread(Foo).Start();
GC.Collect();
Run Code Online (Sandbox Code Playgroud)
是的,可以安全地假设某些东西有对线程的引用,我只是在徘徊究竟是什么.出于某种原因,Reflector没有向我展示System.Threading,所以我不能自己挖掘它(我知道MS发布了.NET框架的源代码,我只是没有它的方便).
我有一个托管的.Net类,它创建了我需要确保正确清理的非托管资源.
我有一个顺序结构:
[StructLayout(LayoutKind.Sequential)]
struct FooBar { ... }
Run Code Online (Sandbox Code Playgroud)
然后在构造函数中我有:
// Allocate the memory
var fb = new FooBar(...);
int length = Marshal.SizeOf(typeof(FooBar));
this.pointer = Marshal.AllocHGlobal(length);
Marshal.StructureToPtr(fb, this.pointer, false);
// Then I use this.pointer in extern calls
Run Code Online (Sandbox Code Playgroud)
然后在我的~Finaliser/ Dispose方法中,我使用Marshal.DestroyStructure或者Marshal.FreeHGlobal两者(如果是这样,以什么顺序)忍受我不泄漏内存?
奖金问题:
IDisposable类是否需要继承CriticalFinalizerObject以确保始终调用清理?Microsoft.Win32.SafeHandles我可以用来包装危险的非托管内存的类?