Command cancellation detection in asynchronous BeginExecuteReader

I have an asynchronous call to the sql command's executeexecutereader method, which the user can cancel. When canceled, I cancel the sqlcommand object and this will kill the job on the sql server.

However, as soon as I canceled it, the callback method specified in the BeginExecute request is called, and when I try to call endexecutequery it throws an error. Result. Finished correctly until the endexecute request is called, at which point it becomes false.

Is there a way to detect command cancellation in a callback method? or should I follow this ...

thanks

+7
source share
2 answers

I deleted and restarted my entire answer: you came across a good case of conflicting documentation and warnings ...

According to the .NET 2.0 MSDN Documentation for SqlCommand.Cancel "The undo method cannot be used to undo a pending asynchronous operation." However, the same documentation for .NET 3.5 does not contain this warning, although it is otherwise identical to the 2.0 documentation.

I would advise you to follow the conventions outlined in the Asynchronous Call to Synchronous Methods , which is designed to delegate .BeginInvoke (not Control.BeginInvoke!) And Delegate.EndInvoke, but are most likely relevant in your case.

Methods called "Begin ... Async" that return IAsyncResult and have the corresponding method "End ..." can create a ThreadPool leak. The easiest way to prevent a leak is to ensure that the appropriate "End ..." method is always called.

The reason is that when Begin ... Async is called, it receives a thread from ThreadPool and (usually) executes a synchronous version of the method in the workflow; in your case ExecuteReader (). The return value of this call or any exceptions that occur during this call are not returned to the main thread until End is called ... - if you never call End, then the results / exceptions never return, and the ThreadPool thread never not exempt.

In short, you'll probably be safe if you call EndExecuteReader () and handle the expected exception. Since the documentation is inconsistent and vague, I started a discussion

+8
source share

Take a quick look at http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98217 for this behavior.

So, it looks like you should just catch this particular exception that was sent to EndExecuteReader and ignore it.

+2
source share

All Articles