I have a private async void Button_Click
method in my WPF which runs a very complicated SQL query which can run for several minutes.
I wish the user can stop this method by clicking another button.
My code is like this:
public partial class MainWindow : Window
{
private async void Button_Click(object sender, RoutedEventArgs e)
{
string SQL_Query= " a very long and complicated SQL query ... "
SqlCommand SQL_Query_cmd = new SqlCommand(SQL_Query, conn);
DataTable dt = new DataTable();
await Task.Run(() => {
using (SqlDataAdapter a = new SqlDataAdapter(SQL_Query_cmd))
{ a.Fill(dt);}
});
}
}
I read about BackgroundWorker
in this link How to use WPF Background Worker.
But didn't understand how to integrate it into my code. I think, my "filling datatable" code is already asynchronous but I don't know how to stop it. Assume that the button which is going to end this method is called stop_btn
and its Click method is called cancelButton_Click
.
Please please please write your answer in a post, rather than comments. I will be greatly thankful.