[英]Throw Exception On UI Thread
我有一個事件處理程序,它給了我一個異常作為參數。 我想在 UI 線程上拋出該參數。 似乎這有時不會在 UI 線程上拋出異常,知道為什么嗎?
_dispatcher = Application.Current.Dispatcher
if (_dispatcher != null && !_dispatcher.CheckAccess())
{
_dispatcher.BeginInvoke((ThreadStart)delegate
{
throw args.Exception;
}, DispatcherPriority.Normal);
return;
}
你的問題很模糊,但看起來像是我最近遇到的一個問題。 出於某些原因,當我從工作線程捕獲異常並嘗試將其重新拋出到 UI 線程時,該異常並未得到處理(盡管具有訂閱DispatcherUnhandledException
事件的高級錯誤管理)並且我的應用程序崩潰了。
這是我的原始代碼
try
{
action(); // Perform task from worker thread
}
catch (Exception ex)
{
var stackBeforDispatch = ex.StackTrace;//get the stack trace before it is dispatched to keep track of the original error origin
var uiThread = Application.Current != null ? Application.Current.Dispatcher : Dispatcher.CurrentDispatcher;//try to find the ui dispatcher if any
Action action1 = action;
//dispatch to ui thread so that the information goes up to the user
uiThread.Invoke(new Action(() =>
{
ex.Source = ex.Source += string.Format("{0}From Thread: {0} {1}{0}From Method: {0} {2}{0}Stack trace before Dispatch: {0} {3}",
Environment.NewLine,
_dispatcherThread.Name,
action1.Method.Name,
stackBeforDispatch);
throw ex;
}));
}
將調度程序優先級更改為較低的優先級,對我而言DispatcherPriority.SystemIdle
似乎解決了這個問題:現在,我在后台線程中發生的所有異常都正確地重新拋出到 UI 線程,在那里它們由DispatcherUnhandledException
處理。
實際上,我不明白為什么,我發現您的問題正在尋找對此的解釋:)
我不確定您在哪里或如何處理此事件,但有時您是否可能已經在 UI 線程上? 在這種情況下,你錯過了另一半。
if (_dispatcher != null)
{
if (!_dispatcher.CheckAccess())
{
//invoke as above
}
else
{
throw args.Exception;
}
}
編輯:也就是說,我同意漢斯的觀點。 如果您向 UI 線程發送異常,誰會捕獲它?
似乎這有時不會在 UI 線程上拋出異常,知道為什么嗎?
因為這:
if (_dispatcher != null && !_dispatcher.CheckAccess())
您不需要 CheckAccess()。
這個問題很老了; 盡管如此,類似的問題現在困擾着我的 UWP 應用程序。 有時,我必須通過允許異常向上傳播來展開調用堆棧。 我需要異常才能到達應用程序的UnhandledException
處理程序,但這並不總是發生。 這個問題包括拋出非 UI 線程的明顯情況。 它還包括一個不明顯的案例,我尚未確定其因果關系,即拋出 UI 線程。
我想到了以下解決方案。 我捕獲異常,然后將其顯式發布到同步上下文。 由於上述奇怪的問題,即使已經在當前同步上下文上運行,我也必須這樣做。 否則,異常有時不會到達UnhandledException
處理程序。
private void Throw( Exception exception )
{
uiContext.Post( arg => throw exception, null );
throw new OperationCanceledException();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.