I have some code I'm downgrading from .NET 4.5's lovely async
and await
keywords to .NET 4.0. I'm using ContinueWith
to create a continuation similar to the way await
works.
Basically, my old code was:
var tokenSource = newCancellationTokenSource();
var myTask = Task.Run(() =>
{
return MyStaticClass.DoStuff(tokenSource.Token);
}, tokenSource.Token);
try
{
var result = await myTask;
DoStuffWith(result);
}
catch (OperationCanceledException)
{
// Cancel gracefully.
}
(As one might expect, MyStaticClass.DoStuff(token)
regularly calls token.ThrowIfCancellationRequested()
.)
My new code looks like this:
var tokenSource = new CancellationTokenSource();
try
{
Task.Factory.StartNew(() =>
{
return MyStaticClass.DoStuff(tokenSource.Token);
}, tokenSource.Token)
.ContinueWith(task =>
{
var param = new object[1];
param[0] = task.Result;
// I need to use Invoke here because "DoStuffWith()" does UI stuff.
Invoke(new MyDelegate(DoStuffWith, param));
});
}
catch (OperationCanceledException)
{
// Cancel gracefully.
}
However, the OperationCanceledException
is never caught. What's going on? Where do I put my try/catch block?