“安全句柄已关闭”线程中止:可以避免程序崩溃吗?

时间:2017-10-04 10:09:00

标签: c# multithreading dll reflection crash

我使用未确定的DLL,它可以使用未确定的资源,如COM端口。 一些DLL方法没有自己的超时,所以我被迫中止执行线程。 但是如果线程正在使用诸如COM端口之类的资源,并且我中止了该线程,则我的程序会因错误“安全句柄已关闭”而崩溃。我知道为什么会发生这种情况,但有没有办法捕获这个异常或跳过它,而不是真正的崩溃?

1 个答案:

答案 0 :(得分:0)

解决方案: 在单独的AppDomain中运行代码会绕过异常并崩溃 - 感谢Sinatr的评论。

代码示例。之前(崩溃)

Work work = new Work();
Thread execThread = new Thread(new ParameterizedThreadStart(work.COM_StartCommand));
execThread.Start("COM4");

Thread.Sleep(5000);
execThread.Abort();

for (int i = 0; i < 1000; i++)
{
    Console.WriteLine("bump" + i); //crashes around iteration 20
    Thread.Sleep(1000);
}

之后:(永不崩溃)

using (Isolated<Work> isolated = new Isolated<Work>())
{
    Thread TestThread = new Thread(new ParameterizedThreadStart(isolated.Value.COM_StartCommand));
    TestThread.Start("COM4");

Thread.Sleep(5000);
TestThread.Abort();
}

for (int i = 0; i < 1000; i++)
{
    Console.WriteLine("bump" + i);
    Thread.Sleep(1000);
}

https://bitlush.com/blog/executing-code-in-a-separate-application-domain-using-c-sharp的启发。 现在我只需要传递变量。