If you recommend use SqlCommand.Cancel(), please give a working example!
I need to show a wait form with a cancel button(if the user clicks this button, the query must stop running) during query execution.
My solution: (.net 4)
I pass to form constructor two parameters:
- query execution task
- cancelation action
Below is code of my loading form:
public partial class LoadingFrm : Form
{
//task for execute query
private Task execute;
//action for cancelling task
private Action cancel;
public LoadingFrm(Task e, Action c)
{
execute = e;
cancel = c;
InitializeComponent();
this.cancelBtn.Click += this.cancelBtn_Click;
this.FormBorderStyle = FormBorderStyle.None;
this.Load += (s, ea) =>
{
//start task
this.execute.Start();
//close form after execution of task
this.execute.ContinueWith((t) =>
{
if (this.InvokeRequired)
{
Invoke((MethodInvoker)this.Close);
}
else this.Close();
});
};
}
//event handler of cancel button
private void cancelBtn_Click(object sender, EventArgs e)
{
cancel();
}
}
Below code of my ExecuteHelper class:
public class ExecuteHelper
{
public static SqlDataReader Execute(SqlCommand command)
{
var cts = new CancellationTokenSource();
var cToken = cts.Token;
cToken.Register(() => { command.Cancel(); });
Task<SqlDataReader> executeQuery = new Task<SqlDataReader>(command.ExecuteReader, cToken);
//create a form with execute task and action for cancel task if user click on button
LoadingFrm _lFrm = new LoadingFrm(executeQuery, () => { cts.Cancel(); });
_lFrm.ShowDialog();
SqlDataReader r = null;
try
{
//(1) here
r = executeQuery.Result;
}
catch (AggregateException ae)
{
}
catch (Exception ex)
{
}
return r;
}
}
But I can't stop execution of SqlCommand
. After some time method that call ExecuteHelper.Execute(command)
get a result (SqlDataReader)
from sql server with data? Why? Anybody can help? How i can cancel execution of sqlcommand?
And i have another question. Why if i click a cancel button of my form and cts.Cancel() was been called //(1) here
i get executeQuery.IsCanceled = false
although executeQuery.Status = Faulted.