[Question] Per thread finalization
We are building C# API for some native library that requires per-thread initialization and cleanup. We can implement initialization using static ThreadLocal data field, i.e.
private static ThreadLocal<HandleHolder> s_handle = new ThreadLocal<HandleHolder>(() => { return new HandleHolder(); });
We can not however use finalizer for cleanup because finalizer runs in GC thread, not original and native library requires that the cleanup should be performed only in the same thread as the initialization. How can we handle this pattern in .NET Core?
We do this today when using libuv by posting work back to the correct thread in ReleaseHandle of our safe handle (https://github.com/aspnet/KestrelHttpServer/blob/5dd590e75ec4b95b03971430696545708e292b35/src/Kestrel.Transport.Libuv/Internal/Networking/UvHandle.cs#L29). Each handle is bound to a particular thread and we store that association on handle creation. When release handle occurs, we post back to the thread (the thread has a queue of work that it picks up and executes) if it’s the incorrect one.
@davidfowl Tank you! Am I right that handle release occurs automatically at thread exit?
No, ReleaseHandle happens when the safe handle is disposed explicitly or finalized. More details here https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.safehandle.releasehandle(v=vs.110).aspx
Thank you.
Question seems answered
@davidfowl
No, ReleaseHandle happens when the safe handle is disposed explicitly or finalized. More details here
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?