如果线程来自另一个进程,如何监听线程退出事件?

时间:2016-09-30 10:01:06

标签: c# .net

如果只给出了线程id,那么当线程退出时,是否可以在.NET中触发方法?

   var windowThreadId = User32.GetWindowThreadProcessId(windowHandle, out processId);

有可能这样做吗? :

 var process = Process.GetProcessById((int)processId);
 process.Exited += (sender, args) =>
 {
     Console.WriteLine("Exited.");
 };

1 个答案:

答案 0 :(得分:0)

所以现在有 this UnmanagedThreadUtils library 可以让您完全实现您的目标:

(官方)示例:

// 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.");
}