2

Lets stay we have the following code:

Var task = Task.Run(() => RunTest(ct.Token));

Void RunTask(CancellationToken token)
{
If (!token.IsCancellationRequested)
}

 Cmd.CommandText = code;
 Cmd.ExecuteNonQuery();
}
}

This does now cancel a long running SQL query which is running, how can I immediately kill the task if Cancellation is requested and terminate the long running SQL query? I know about the 'Cancel()' but how can I trigger it based on the cancellationToken?

Time Machine
  • 157
  • 1
  • 14
  • Possible duplicate of [Stop SQL query execution from .net Code](http://stackoverflow.com/questions/4779679/stop-sql-query-execution-from-net-code) – Ondrej Svejdar Mar 08 '16 at 11:13

2 Answers2

3

If you use ExecuteNonQuery then the thread that your task is running on is waiting somewhere in someone else's code - it's not available for you to commandeer and do other work with.

But the good news is, you don't need it to be. Just use ExecuteNonQueryAsync instead and let the SqlCommand object handle cancellation itself.

async Task RunTask(CancellationToken token)
{
  Cmd.CommandText = code;
  await Cmd.ExecuteNonQueryAsync(token);
}

You may also want to Unwrap what's in your task variable at this stage, since it's now a Task<Task> and usually, if you're interested at all, you'd be interested in when the inner Task is complete.

Or you may want to consider whether Task.Run is required at all. That depends on why the Task.Run was inserted into your sample in the first case and on how much actual activity RunTask is performing.

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
0

To cancel a SqlCommand you should use SqlCommand.Cancel() method

take a look here : https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.cancel.aspx

Quentin Roger
  • 6,410
  • 2
  • 23
  • 36