I have the following piece of code:
IAsyncResult beginExecuteReader = command.BeginExecuteNonQuery();
while (!beginExecuteReader.IsCompleted)
{
if (controllerTask.CancellationTokenSource.IsCancellationRequested)
{
command.Cancel();
}
Thread.Sleep(100);
}
try
{
result = command.EndExecuteNonQuery(beginExecuteReader);
}
catch (SqlException exception)
{
if (exception.ErrorCode == OperationCanceled)
{
throw new OperationCanceledException();
}
throw;
}
How can I identify that the exception caught was caused by operation cancelation?
In this case ExecuteNonQuery throws an exception with error code 0x80131904, but it's a very general exception which can be caused by many reasons. The error message looks like this: "A severe error occurred on the current command. The results, if any, should be discarded.\r\nOperation cancelled by user."
I don't see any options except parsing the error message... Any ideas?
Thanks
PS. Yeah, I know that using the Cancel command for async operation probably is not the best idea, because in the .NET 2.0 documentation on MSDN there was a warning. But in the .NET 4.0 documentation, this warning is removed.
I also don't like other implementations where the cancel method is called from another thread, as for me it makes code more difficult.