Task and exception silence

前端 未结 4 650
暗喜
暗喜 2021-02-04 04:04

Why exceptions thrown within a task are silent exception and you never know if a certain exception has been thrown

try
{

 Task task = new Task(
  () => {
            


        
4条回答
  •  天涯浪人
    2021-02-04 04:25

    The behaviour of that scenario depends on what framework you have; in 4.0, you actually need to be careful - if you don't handle TaskScheduler.UnobservedTaskException, it will error later when it gets collected/finalized, and will kill your process.

    TaskScheduler.UnobservedTaskException += (sender, args) =>
    {
        Trace.WriteLine(args.Exception.Message); // somebody forgot to check!
        args.SetObserved();
    };
    

    This changes in 4.5, IIRC.

    To check the outcome of a Task that might fail, you could register a continuation - i.e. call ContinueWith and check the result's exception. Alternatively, accessing the .Result of the task (which would also do an implicit Wait()) will re-surface the exception that happened. It is good to observe the result of a task, as that clears the finalization flag, meaning it can be collected more cheaply.

提交回复
热议问题