This recipe describes the very important topic of handling exceptions in asynchronous tasks. We will go through different aspects of what happens to exceptions thrown from tasks and how to get to their information.
To step through this recipe, you will need Visual Studio 2012. There are no other prerequisites. The source code for this recipe can be found at BookSamples\Chapter4\Recipe7
.
For handling exceptions in tasks, perform the following steps:
Start Visual Studio 2012. Create a new C# Console Application project.
In the
Program.cs
file, add the followingusing
directives:using System; using System.Threading; using System.Threading.Tasks;
Add the following code snippet below the
Main
method:static int TaskMethod(string name, int seconds){ Console.WriteLine("Task {0} is running on a thread id{1}. Is thread pool thread: {2}", name,Thread.CurrentThread.ManagedThreadId,Thread.CurrentThread.IsThreadPoolThread); Thread.Sleep(TimeSpan...