问题描述
我使用不确定的DLL,这些DLL可以使用不确定的资源(例如COM端口).一些DLL方法没有自己的超时,因此我被迫中止执行线程.但是,如果线程正在使用COM端口等资源,而我中止了线程,则程序将崩溃,并显示错误安全句柄已关闭".我知道为什么会发生这种情况,但是有什么办法可以捕捉到该异常或将其跳过,而不是实际崩溃吗?
Im using undetermined DLLs which can use undetermined resources such as a COM port.Some DLL methods don't have their own timeouts, so i am forced to abort the execution thread.But if the thread is using a resource such as a COM port, and i abort the thread, my program crashes with the error "Safe handle has been closed". I know why this happens but is there any way to catch this exception or skip it, rather than an actual crash?
推荐答案
解决方案:在注释中感谢Sinatr.在单独的AppDomain中运行代码会绕过异常和崩溃.
Solution:Running the code in a separate AppDomain bypasses the exception and crash - thanks to Sinatr in the comments.
代码示例.之前(崩溃)
Code example. Before (crashed)
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 .现在,我只需要传递变量.
Inspired by https://bitlush.com/blog/executing-code-in-a-separate-application-domain-using-c-sharp.Now I just need to pass around variables.
这篇关于“安全句柄已关闭"线程中止:是否可以避免程序崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!