問題描述
這是什么意思以及如何解決?
我正在使用 TPL 任務.
整個錯誤
<塊引用>在等待任務或訪問其異常屬性時未觀察到任務的異常.結果,未觀察到的異常被終結器線程重新拋出.
在 System.Threading.Tasks.TaskExceptionHolder.Finalize()
mscorlib
如果你創建了一個任務,并且你沒有調用 task.Wait()
或者嘗試檢索一個任務的結果Task<T>
,當垃圾收集器收集到任務時,它會在終結期間關閉你的應用程序.有關詳細信息,請參閱 TPL 中的異常處理 上的 MSDN 頁面..p>
這里最好的選擇是處理"異常.這可以通過延續來完成 - 您可以將延續附加到任務,并記錄/吞下/等發生的異常.這提供了一種干凈的方式來記錄任務異常,并且可以寫成一個簡單的擴展方法,即:
public static void LogExceptions(this Task task){task.ContinueWith(t =>{var aggException = t.Exception.Flatten();foreach(aggException.InnerExceptions 中的 var 異常)日志異常(異常);},TaskContinuationOptions.OnlyOnFaulted);}
通過上述方法,您可以防止任何任務通過以下方式關閉應用程序并記錄它:
Task.Factory.StartNew(() =>{//做你的工作...}).LogExceptions();
或者,您可以訂閱 TaskScheduler.UnobservedTaskException 并在那里處理它.
What does this mean and how to resolve it?
I am using TPL tasks.
The whole error
A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread.
at System.Threading.Tasks.TaskExceptionHolder.Finalize()
mscorlib
If you create a Task, and you don't ever call task.Wait()
or try to retrieve the result of a Task<T>
, when the task is collected by the garbage collector, it will tear down your application during finalization. For details, see MSDN's page on Exception Handling in the TPL.
The best option here is to "handle" the exception. This can be done via a continuation - you can attach a continuation to the task, and log/swallow/etc the exception that occurs. This provides a clean way to log task exceptions, and can be written as a simple extension method, ie:
public static void LogExceptions(this Task task)
{
task.ContinueWith( t =>
{
var aggException = t.Exception.Flatten();
foreach(var exception in aggException.InnerExceptions)
LogException(exception);
},
TaskContinuationOptions.OnlyOnFaulted);
}
With the above, you can prevent any task from tearing down the app, and logging it, via:
Task.Factory.StartNew( () =>
{
// Do your work...
}).LogExceptions();
Alternatively, you can subscribe to the TaskScheduler.UnobservedTaskException and handle it there.
這篇關于通過等待任務或訪問其異常屬性未觀察到任務的異常.結果,未觀察到的異常是的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!