如何终止在非托管代码中阻止的托管线程?

Jam*_*ran 7 .net c# multithreading

我有一个在等待,阻塞,在非托管代码托管的线程(具体地说,到NamedPipeServerStream.WaitForConnection()的调用ultimitely非托管代码,并没有一个电话提供超时).

我想整齐地关闭线程.

Thread.Abort()在代码返回托管领域之前没有任何效果,在客户端建立连接之前它不会这样做,我们不能等待.

我需要一种从非托管代码中"震惊"的方法; 或者即使它处于未管理的土地上也只是杀死线程的方法.

dtb*_*dtb 19

您是否尝试过使用非阻塞的NamedPipeServerStream.BeginWaitForConnection方法?

using (NamedPipeServerStream stream = ...)
{
    var asyncResult = stream.BeginWaitForConnection(null, null);

    if (asyncResult.AsyncWaitHandle.WaitOne(5000))
    {
        stream.EndWaitForConnection(asyncResult);
        // success
    }
}
Run Code Online (Sandbox Code Playgroud)

您不一定要使用固定超时.您可以使用ManualResetEvent来指示线程何时应该停止等待连接:

ManualResetEvent signal = new ManualResetEvent(false);

using (NamedPipeServerStream stream = ...)
{
    var asyncResult = stream.BeginWaitForConnection(_ => signal.Set(), null);

    signal.WaitOne();
    if (asyncResult.IsCompleted)
    {
        stream.EndWaitForConnection(asyncResult);
        // success
    }
}

// in other thread
void cancel_Click(object sender, EventArgs e)
{
    signal.Set();
}
Run Code Online (Sandbox Code Playgroud)