Reputation: 23833
I have the following task
cancelSource = new CancellationTokenSource();
token = cancelSource.Token;
string strDbA = textBox1.Text;
string strDbB = textBox2.Text;
// Start duplication on seperate thread.
asyncDupSqlProcs =
new Task<bool>(state =>
UtilsDB.DuplicateSqlProcsFrom(token, mainForm.mainConnection, strDbA, strDbB), "Duplicating SQL Proceedures");
asyncDupSqlProcs.Start();
asyncDupSqlProcs.ContinueWith(task =>
{
switch (task.Status)
{
// Handle any exceptions to prevent UnobservedTaskException.
case TaskStatus.Faulted:
// Error-handling logic...
break;
case TaskStatus.RanToCompletion:
if (asyncDupSqlProcs.Result)
Utils.InfoMsg(String.Format(
"SQL stored procedures and functions successfully copied from '{0}' " +
"to '{1}'", strDbA, strDbB));
break;
case TaskStatus.Canceled:
Utils.InfoMsg("Copy cancelled at users request.");
break;
}
}, TaskScheduler.FromCurrentSynchronizationContext());
In the method DuplicateSqlProcsFrom(token, mainForm.mainConnection, strDbA, strDbB)
I have the standard cancellation detection:
if (_token.IsCancellationRequested)
_token.ThrowIfCancellationRequested();
The cancellation event is a button click on the main form, inside the click event I have:
try
{
cancelSource.Cancel();
asyncDupSqlProcs.Wait();
}
catch (AggregateException aggEx)
{
if (aggEx.InnerException is OperationCanceledException)
Utils.InfoMsg("Copy cancelled at users request.");
}
but I can seem to catch the AggregateException
, what am I doing wrong here?
Edit: Inside the method DuplicateSqlProcsFrom(token, mainForm.mainConnection, strDbA, strDbB)
I can catch the OperationCancelledException
but I am confused about how to handle it. All the example I have seen handle the printing of "Operation Cancelled..." etc. on the UI thread within the event that caused the cancel. What is the best way to capture the cancel and pass it back to the UI/calling thread?
Upvotes: 4
Views: 802
Reputation: 23833
To get an OperationCancelledException
, it needs to be thrown with the same token as the one passed to the Task's constructor:
new Task<bool>(state =>
UtilsDB.DuplicateSqlProcsFrom(token, mainForm.mainConnection, strDbA, strDbB),
"Duplicating SQL Proceedures", token);
Upvotes: 1
Reputation: 6554
It most likely has to do with Just My Code mode (defaulted to checked) in Visual Studio. The debugger is breaking before the TPL can observe the exception. Try unchecking the box and see if that clears things up (Tools->Options->Debugging->General, then un-check the box)
Upvotes: 2