Exception Handling: v / s Task

The result of the page version results in an unhandled exception that causes the application to crash, but the task version does not work. Both work the exact same way. Can someone explain the reason for this difference in exception behavior?

Topic Version:

            try
            {
                new Thread(new ThreadStart(DoWork)).Start();  // do work throws exception
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

        static void DoWork()
        {
            Console.WriteLine("in thread");
            throw new Exception();
        }

Task Version:

      var errorTask = Task.Factory.StartNew<Func<string>>(() =>
                {
                    Console.WriteLine("in task");
                    throw new Exception();
                });

            try
            {
                string result = errorTask.Result();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
+4
source share
2 answers

Thread.Start starts a new thread, but you are handling the exception in another thread:

try
{
    // DoWork throws exception in new thread;
    // threads don't catch exceptions out-of-the-box
    new Thread(new ThreadStart(DoWork)).Start();
}
catch (Exception e)
{
    // you're handling exception in "old" thread
    Console.WriteLine(e);
}

Task.Factory.StartNewa new task starts. The task throws an exception inside it to set the property Status:

var errorTask = Task.Factory.StartNew<Func<string>>(() =>
{
    Console.WriteLine("in task");

    // this exception will be caught in Task base code,
    // since tasks catch exceptions thrown by task methods;
    // note, that this will be wrapped into AggregateException
    throw new Exception();
});

when you try to receive Task.Result, and the task is in a failed state, it just throws an exception:

// this will re-throw exception in calling thread
string result = errorTask.Result;

That's why your second catchcatches him.

+3
source

, Task.Result<TResult>() ( Task.Wait() , ).

( AggregateException)

. AggregateException.InnerExceptions .

A Task - ( ), , . Result Wait ( await). , Thread , . a (), try / catch. , try / catch. , . , , , try / catch .

+1

Source: https://habr.com/ru/post/1689224/


All Articles