我正在尝试在我的WPF
应用程序中实现加载器。在一些繁重的操作中,UI 线程被冻结,所以我不得不使用线程来实现加载器。每次加载程序加载时,都会创建一个新线程,并且当加载程序启动时,该线程会(手动)中止。我面临的问题是,有时应用程序会崩溃并给出ThreadAbortException
.
这是启动加载程序的代码:
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