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?
To get an
OperationCancelledException, it needs to be thrown with the same token as the one passed to the Task’s constructor: