to cancel query you need run the query as a task. then cancel via the token
int SecDelete = 20000;
CancellationTokenSource cts = new CancellationTokenSource();
private void STOP_QUERY_Click(object sender, EventArgs e)
{
CancelQuery();
}
private void START_QUERY_Click(object sender, EventArgs e)
{
DoQuery();
}
private voicemail CancelQuery()
{
cts.Cancel();
cts = new CancellationTokenSource();
}
private async Task DoQuery()
{
var watchTask = Task.Run(() => Thread.Sleep(SecDelete));
using (SqlConnection cn = new SqlConnection(connectionString))
{
cn.Open();
// Execute the command
using (SqlCommand cmd = new SqlCommand(commandText, cn))
{
try
{
var sqlTask = cmd.ExecuteNonQueryAsync(cts.Token);
await Task.WhenAny(sqlTask, watchTask);
if (!sqlTask.IsCompleted)
{
CancelQuery(); // kill query
throw new Exception("killed query");
}
var activityCount = sqlTask.Result;
// run on ui thread - check docs for calling dispatcher
Invoke(() => MessageBox.Show(activityCount.ToString());
}
catch (Exception ex)
{
}
Invoke(() => MessageBox.Show(message));
}
}
}
```