Ref*_*din 5 .net c# multithreading error-suppression thread-abort
我的程序加载时,我在后台线程上显示启动画面.加载后我将中止Thread,因为它的唯一目的是显示一个Now Loading飞溅表单.
我的问题是,当中止一个Thread时,它会抛出一个ThreadAbortException用户只需单击Continue on.
我该如何处理?我试图压制它 - >
try
{
Program.splashThread.Abort();
}
catch(Exception ex)
{
}
Run Code Online (Sandbox Code Playgroud)
但我有一种感觉,这会让我在这里大吼大叫,它无论如何都行不通.
谢谢!
Fre*_*örk 20
您无需取消该帖子.我将用代码举例说明.
在启动画面中:
public void CloseSplash()
{
Invoke((MethodInvoker)delegate
{
this.Close();
});
}
Run Code Online (Sandbox Code Playgroud)
在Program.cs文件中:
private static Splash _splash = null;
public static void CloseSplash()
{
if (_splash!= null)
{
_splash.CloseSplash();
}
}
Run Code Online (Sandbox Code Playgroud)
现在,当Main方法启动时,在线程中显示启动:
Thread t = new Thread(new ThreadStart(delegate
{
_splash = new Splash();
_splash.ShowDialog();
}));
t.Start();
Run Code Online (Sandbox Code Playgroud)
...当你想要它关闭时,只需关闭它:
Program.CloseSplash();
Run Code Online (Sandbox Code Playgroud)
然后你不必担心中止线程; 它会优雅地退出.
请参阅以下链接获取Google搜索(返回的第一个结果):
http://msdn.microsoft.com/en-us/library/5b50fdsz.aspx
特别注意这部分:
在线程上调用此方法时,系统会在线程中抛出ThreadAbortException以中止它.ThreadAbortException是一个特殊的异常,可以被应用程序代码捕获,但是在catch块的末尾重新抛出,除非调用ResetAbort.ResetAbort取消中止请求,并阻止ThreadAbortException终止线程.在线程中止之前执行未执行的finally块.
不建议使用Threadabort.这是邪恶的.为什么不使用像(自动/手动)ResetEvent这样的其他机制?使用启动画面启动线程,等待事件.如果其他代码已完成加载内容,请设置事件以允许启动屏幕以正常(好)方式关闭自身.