Unmanaged thread utils for .NET
- Provides a way to subscribe to a Thread Exit event
- The event is fired on the Thread that is about to exit
- Cross-platform (Windows, Linux, MacOS)
Example:
// Use static field to make sure that delegate is alive.privatestaticreadonlyUnmanagedThread.ThreadExitCallbackThreadExitCallbackDelegate=OnThreadExit;publicstaticvoidMain(){varthreadExitCallbackDelegatePtr=Marshal.GetFunctionPointerForDelegate(ThreadExitCallbackDelegate);varcallbackId=UnmanagedThread.SetThreadExitCallback(threadExitCallbackDelegatePtr);for(vari=1;i<=ThreadCount;i++){varthreadLocalVal=i;varthread=newThread(_ =>{Console.WriteLine($"Managed thread #{threadLocalVal} started.");UnmanagedThread.EnableCurrentThreadExitEvent(callbackId,newIntPtr(threadLocalVal));});thread.Start();}UnmanagedThread.RemoveThreadExitCallback(callbackId);}privatestaticvoidOnThreadExit(IntPtrdata){Console.WriteLine($"Unmanaged thread #{data.ToInt64()} is exiting.");}