我想在我的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