Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

c# - “Safe handle has been closed” Thread abort: can program crash be avoided?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

After: (never crash)

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);
}

Inspired by https://bitlush.com/blog/executing-code-in-a-separate-application-domain-using-c-sharp. Now I just need to pass around variables.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...