How to cancel a long-running Database operation?

If you’re using ADO.NET and SQL data provider, take a look at SqlCommand.Cancel method. That does what you’re looking for. However, it tries to cancel and the cancellation may take time. Basically, it’s up to SQL Server to decide when to grant your cancellation request. When the query is cancelled, you should get a SqlException that indicates that the operation was cancelled by user. Apparently, you don’t want to treat this exception as exception and handle it specially such as if SqlException is due to user cancelling the operation, just swallow it.

Leave a Comment