[Question] Per thread finalizer
Regarding https://github.com/dotnet/corefx/issues/26992, I have a question.
@davidfowl
No, ReleaseHandle happens when the safe handle is disposed explicitly or finalized.
If we cannot dispose the safe handle explicitly, only finalizer can release it. In this situation, is there a way that the safe handle is disposed by finalizer in the same thread as initialization?
I don't believe there's a way to do that.
If so, it's the best solution that thread local unmanaged memory should be released by explictly calling Dispose(). right?
Dispose doesn't guarantee that the safe handle (if you choose to use one) will be disposed on the right thread. If you're in the middle of a pinvoke, dispose will be queued to run later so you don't AV. If you own the object then you can explicitly dispose it on the correct thread.
Let me summarize our module.
class Net provides all methods as static and internally keeps only single instance of NetImpl class. NetImpl class should have a handle (it's a SafeHandle) to use the (unmanaged) native codes. The handle is managed as thread local in native.
class Net
{
public static Method() {
NetImpl.Instance.Method();
}
}
class NetImpl
{
private static ThreadLocal<HandleHolder> s_threadName = new ThreadLocal<HandleHolder>(() = new HandleHolder());
internal SafeNetHandle GetHandle() { return s_threadName.Value.GetSafeHandle(); }
internal void Method()
{
Interop.Net.Method(GetHandle());
}
}
public sealed class SafeNetHandle : SafeNetHandle
{
protected override bool ReleaseHandle()
{
Interop.Net.Deinit(this.handle); // release unmanaged memory
}
}
internal class HandleHolder
{
private SafeNetHandle handle;
internal HandleHolder()
{
handle = Interop.Net.Init(); // initialize native codes
}
internal SafeNetHandle GetSafeHandle() { return handle; }
}
In order to release unmanaged memory in multi-thread environments, should we provide a method like ReleaseResources() in Net class? When each thread exits, we must call ReleaseResources(). Please let me know if there is another way. Thanks.
I think the only way to do that is to create your own threads so that you can be in full control over the lifetime, especially if the initialize, use, and release of the unmanaged resource needs to all happen on one thread.
@kouvel even then you can't guarantee it will run on the right thread. You need to use your own thread and use avoid using a safe handle if you want full control.
Ya that's true