UnmanagedThreadUtils 1.0.0

Provides a way to subscribe to a Thread Exit event

Install-Package UnmanagedThreadUtils -Version 1.0.0
dotnet add package UnmanagedThreadUtils --version 1.0.0
<PackageReference Include="UnmanagedThreadUtils" Version="1.0.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add UnmanagedThreadUtils --version 1.0.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
  • 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.
private static readonly UnmanagedThread.ThreadExitCallback ThreadExitCallbackDelegate = OnThreadExit;

public static void Main()
{
    var threadExitCallbackDelegatePtr = Marshal.GetFunctionPointerForDelegate(ThreadExitCallbackDelegate);
    var callbackId = UnmanagedThread.SetThreadExitCallback(threadExitCallbackDelegatePtr);

    for (var i = 1; i <= ThreadCount; i++)
    {
        var threadLocalVal = i;

        var thread = new Thread(_ =>
        {
            Console.WriteLine($"Managed thread #{threadLocalVal} started.");
            UnmanagedThread.EnableCurrentThreadExitEvent(callbackId, new IntPtr(threadLocalVal));
        });

        thread.Start();
    }

    UnmanagedThread.RemoveThreadExitCallback(callbackId);
}

private static void OnThreadExit(IntPtr data)
{
    Console.WriteLine($"Unmanaged thread #{data.ToInt64()} is exiting.");
}
  • 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.
private static readonly UnmanagedThread.ThreadExitCallback ThreadExitCallbackDelegate = OnThreadExit;

public static void Main()
{
    var threadExitCallbackDelegatePtr = Marshal.GetFunctionPointerForDelegate(ThreadExitCallbackDelegate);
    var callbackId = UnmanagedThread.SetThreadExitCallback(threadExitCallbackDelegatePtr);

    for (var i = 1; i <= ThreadCount; i++)
    {
        var threadLocalVal = i;

        var thread = new Thread(_ =>
        {
            Console.WriteLine($"Managed thread #{threadLocalVal} started.");
            UnmanagedThread.EnableCurrentThreadExitEvent(callbackId, new IntPtr(threadLocalVal));
        });

        thread.Start();
    }

    UnmanagedThread.RemoveThreadExitCallback(callbackId);
}

private static void OnThreadExit(IntPtr data)
{
    Console.WriteLine($"Unmanaged thread #{data.ToInt64()} is exiting.");
}

This package is not used by any popular GitHub repositories.

Version History

Version Downloads Last updated
1.0.0 157 10/3/2019