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

栏目: ASP.NET · 发布时间: 6年前

内容简介:我有一个托管线程,它在一个非托管代码中等待,阻塞(具体来说,它在调用NamedPipeServerStream.WaitForConnection()时会最终调用非托管代码,并且不提供超时).我想整齐地关闭线程.Thread.Abort()在代码返回到托管领域之前没有任何效果,在客户端建立连接之前它不会这样做,我们不能等待.

我有一个托管线程,它在一个非托管代码中等待,阻塞(具体来说,它在调用NamedPipeServerStream.WaitForConnection()时会最终调用非托管代码,并且不提供超时).

我想整齐地关闭线程.

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

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

您是否尝试过使用非阻塞 NamedPipeServerStream.BeginWaitForConnection 方法?
using (NamedPipeServerStream stream = ...)
{
    var asyncResult = stream.BeginWaitForConnection(null, null);

    if (asyncResult.AsyncWaitHandle.WaitOne(5000))
    {
        stream.EndWaitForConnection(asyncResult);
        // success
    }
}

您不一定要使用固定超时.当线程停止等待连接时,您可以使用 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();
}

翻译自:https://stackoverflow.com/questions/2700472/how-to-terminate-a-managed-thread-blocked-in-unmanaged-code


以上所述就是小编给大家介绍的《c# – 如何终止在非托管代码中阻止的托管线程?》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms of the Intelligent Web

Algorithms of the Intelligent Web

Haralambos Marmanis、Dmitry Babenko / Manning Publications / 2009-7-8 / GBP 28.99

Web 2.0 applications provide a rich user experience, but the parts you can't see are just as important-and impressive. They use powerful techniques to process information intelligently and offer featu......一起来看看 《Algorithms of the Intelligent Web》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

SHA 加密
SHA 加密

SHA 加密工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具