10

I'm executing one stored procedure from the '.net' code. Since there is a lot of data, it is taking too much time to execute. Is there any way to stop this execution from the c# code?

In other words, if we execute the query from database itself, there is a option to stop its execution but in the code is it possible?

NaveenBhat
  • 3,248
  • 4
  • 35
  • 48

3 Answers3

17

Yes sqlcommand.cancel is your friend http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.cancel.aspx

stefan
  • 2,886
  • 21
  • 27
  • 1
    Apparently closing the command is more likely to work 100% of the time: http://stackoverflow.com/questions/889102/how-to-cancel-a-long-running-database-operation/3699391#3699391 – user423430 Oct 07 '11 at 18:04
11

Yes, you can cancel the query by using SqlCommand.Cancel. However, the command must be running in another thread (otherwise Cancel will be called only after the command is finished).

Also you can specify a CommandTimeout if you want to cancel this query when it runs over a specified time limit.

Andrey Shchekin
  • 21,101
  • 19
  • 94
  • 162
  • the command must be running in another thread ? real world sample ? – Kiquenet Dec 30 '18 at 13:50
  • 1
    FWIW, setting the `CommandTimeout` doesn't cancel the query on the database server for MySQL. It just ends the waiting in the client. This needs to be called explicitly @ [MySql Connector/Connection.cs](https://github.com/mysql/mysql-connector-net/blob/5864e6b21a8b32f5154b53d1610278abb3cb1cee/Source/MySql.Data/Connection.cs#L681). – Peter Majeed Dec 08 '20 at 17:12
1

You can do myCommand.Cancel(), and this will work best as even i have face similar issue in past, and using myCommand.Cancel() i have solved my issue. :) :)

Cheetah
  • 86
  • 8