What is the best way to catch the "Operation canceled by user" exception

I have the following 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 determine that the detected exception is caused by the cancellation of the operation. In this case, ExecuteNonQuery throws an exception with error code 0x80131904, but this is a very general exception, which can be caused by many reasons. The error message looks like this: {"A strong error has occurred in the current command. Results, if any, should be discarded. \ R \ nCancel canceled by user." }

I see no parameters other than parsing the error message ... Any ideas?

thank

PS. , , Cancel asyncronyc, , , .NET 2.0 MSDN , .NET 4.0 . , ,

+5
2

, :

  • , ado ( )
  • Thread.Sleep(100);//
  • static bool muststop = false;
  • , ""
  • , , muststop == true

,

0

catch, , :

try
{
   //your code
}
catch (SqlException ex)
{
  if (ex.Message.Contain("Operation cancelled by user"))
   {
       //Do something here
   }
}
-1

All Articles