I am using the new async await features to upgrade from backgroundworker in C#. In the following code I am trying to replicate the execution of multiple tasks with ContinueW
When you use Task.Wait()
, you are basically saying "wait here my task to complete". That's why you are blocking the thread. A good way to handle exception in tasks is using the Task.ContinueWith
overload and pass OnlyOnFaulted
as TaskContinuationOption
which would look like:
Task yourTask = new Task {...};
yourTask.ContinueWith( t=> { /*handle expected exceptions*/ }, TaskContinuationOptions.OnlyOnFaulted );
If this is running within a UI event handler, you can add the async
modifer to the method signature and change t1.Wait()
to await t1
. This will return control to the UI thread, and when the Thread.Sleep has completed, the continuation will execute and any exceptions will be caught.
If you're going to use the Task-based Asynchronous Pattern, then you should use the recommended guidelines. I have an MSDN article describing many of them.
In particular:
Task.Run
instead of the Task
constructor with Task.Start
.await
instead of ContinueWith
.AttachedToParent
.If you apply these changes, your code will then look like this:
try
{
await Task.Run(() =>
{
Thread.Sleep(10000);
// make the Task throw an exception
MessageBox.Show("This is T1");
});
await Task.Run(() =>
{
Thread.Sleep(1000);
MessageBox.Show("This is Continuation");
});
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}