TimeoutException, TaskCanceledException C #

I am new to C # and I find exceptions a bit confusing ... I have a web application with the following code:

try { //do something } catch (TimeoutException t) { Console.WriteLine(t); } catch (TaskCanceledException tc) { Console.WriteLine(tc); } catch (Exception e) { Console.WriteLine(e); } 

When I debug the code, it throws an e Exception , the most common, and when I find the exception information, it turns out that it is a TaskCanceledException . Why did not catch TaskCanceledException ? If the exception was a TimeoutException , would it catch a TimeoutException or would it also catch an Exception ? Why is this?

+7
c # exception-handling timeoutexception
source share
1 answer

When catching an Exception you need to make sure that it is a precisely thrown exception. When using Task.Run or Task.Factory.Startnew and usually including an exception that is thrown from the Task (if the task is not expected using the await keyword), the external exception you are dealing with is an AggregateException , since the Task block may have child tasks that may also throw exceptions.

From Exception Handling (parallel task library) :

Unhandled exceptions that are triggered by user code that runs inside a task propagate back to the connection thread, with the exception of certain scenarios described later in this section. Exceptions are thrown when using one of the static or instances of Task.Wait or Task.Wait, and you handle them by including a call in a try-catch statement. If the task is the parent of the attached child of the task, or if you expect multiple tasks, then several exceptions may be thrown. To extend all exceptions to the calling thread, the task infrastructure wraps them in an AggregateException instance. AggregateException Property of InnerExceptions that can be enumerated to examine all the original exceptions that have been thrown and to process (or not to process) each one individually. Even if only one exception is thrown, it is still wrapped in an AggregateException.

So, to handle this, you have to catch an AggregateException :

 try { //do something } catch (TimeoutException t) { Console.WriteLine(t); } catch (TaskCanceledException tc) { Console.WriteLine(tc); } catch (AggregateException ae) { // This may contain multiple exceptions, which you can iterate with a foreach foreach (var exception in ae.InnerExceptions) { Console.WriteLine(exception.Message); } } catch (Exception e) { Console.WriteLine(e); } 
+6
source share

All Articles