Stop SQL query execution from .net Code
Yes sqlcommand.cancel is your friend http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.cancel.aspx
How i can stop sql query execution from .net code?
Instead of calling ExecuteReader
call ExecuteReaderAsync
and pass in the CancellationToken
.
If you are on .net 4.0 you can write your own ExecuteReaderAsync
using a TaskCompletionSource
. I haven't tested this code, but it should roughly be this:
public static class Extensions
{
public static Task<SqlDataReader> ExecuteReaderAsync(this SqlCommand command, CancellationToken token)
{
var tcs = new TaskCompletionSource<SqlDataReader>();
// whne the token is cancelled, cancel the command
token.Register( () =>
{
command.Cancel();
tcs.SetCanceled();
});
command.BeginExecuteReader( (r) =>
{
try
{
tcs.SetResult(command.EndExecuteReader(r));
}
catch(Exception ex)
{
tcs.SetException(ex);
}
}, null);
return tcs.Task;
}
}
You are using the SqlCommand.Cancel
method to cancel any async operation in progress. Then you can use it like this:
public static SqlDataReader Execute(SqlCommand command)
{
SqlDataReader r = null;
var cts = new CancellationTokenSource();
var cToken = cts.Token;
var executeQuery = command.ExecuteReaderAsync(cToken).
.ContinueWith( t =>
{
if(t.IsCompleted)
{
r = t.Result;
}
}, TaskScheduler.Default);
//create a form with execute task and action for cancel task if user click on button
LoadingFrm _lFrm = new LoadingFrm(executeQuery, () => { cts.Cancel(); });
// Assuming this is blocking and that the executeQuery will have finished by then, otheriwse
// may need to call executeQuery.Wait().
_lFrm.ShowDialog();
return r;
}
I modified the Execute
method to use ContunueWith
rather than r.Result
because Result
is a blocking property and you'll not show the dialog until the query is complete.
As mentioned it is untested, but should be pretty close to what you need.
C# Cancel a list of tasks which are executing long running sql queries
You need to use CancellationToken inside of functions passed as Action instances to EnqueueTask method.
E.g. the following code shows how CancellationToken can be used for terminating execution of SQL commands:
using (SqlConnection conn = new SqlConnection(sqlConnection))
{
conn.Open();
var cmd = conn.CreateCommand();
using (cancellationToken.Register(() => cmd.Cancel()))
{
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
}
Related Topics
How Can Xml Documentation for Web API Include Documentation from Beyond the Main Project
Cleanest Way to Invoke Cross-Thread Events
Why Use Asqueryable() Instead of List()
Stream.Seek(0, Seekorigin.Begin) or Position = 0
How to Check If Int Is Legal Enum in C#
How to Find the Mode in Array C#
Use Dbcontext in Asp .Net Singleton Injected Class
How to Set a Conditional Compile Variable
.Net Core Identity Server 4 Authentication VS Identity Authentication
Private Inner Classes in C# - Why Aren't They Used More Often
ASP.NET MVC - How to Show Unauthorized Error on Login Page
Will the Base Class Constructor Be Automatically Called
How to Grant Full Permission to a File Created by My Application for All Users
Should I Worry About "This Async Method Lacks 'Await' Operators and Will Run Synchronously" Warning
Using SQLdataadapter to Insert a Row
Sending an Array of Values to Oracle Procedure to Use in Where in Clause