我想在我的WPF
应用程序中实现装载器。在一些繁重的操作中,UI线程被冻结,所以我必须使用线程来实现加载器。每次加载器加载时,都会创建一个新线程,并且在加载器启动时该线程会中止(手动)。我面临的问题是,有时应用程序崩溃给出ThreadAbortException
。WPF中的线程异常终止
这是启动加载器代码:
try
{
//if(newWindowThread !=null && !newWindowThread.IsAlive) { }
newWindowThread = new Thread(new ThreadStart(() =>
{
try
{
// Create and show the Window
awq = new BusyIndicatorDisguise(BusyMessage);
awq.Show(); // <== POINT WHERE THE EXCEPTION IS THROWN
//Start the Dispatcher Processing
if (!isDispatcherStarted)
{
var a = Thread.CurrentThread;
var b = Dispatcher.CurrentDispatcher;
//isDispatcherStarted = true;
Dispatcher.Run();
}
}
catch (ThreadAbortException thEx)
{
}
catch (Exception ex)
{
}
}
));
// Set the apartment state
newWindowThread.SetApartmentState(ApartmentState.STA);
// Make the thread a background thread
newWindowThread.IsBackground = true;
// Start the thread
newWindowThread.Start();
}
catch (Exception ex)
{
}
此代码是用于停止装载机:
if (newWindowThread != null && newWindowThread.IsAlive)
{
newWindowThread.Abort();
}
我不能够赶上这个例外在我的catch块。也许是因为它在不同的线程上。 我想知道如何避免ThreadAbortException
考虑使用CancellationToken而不是中止线程。 – yaakov