I was wondering why the exception in this Click
event is not being caught? Nothing fancy in the code, except for statusLabel
displaying the status of the process to the user. myDataTable
is a local variable; the goal is to assign the result to it.
Does GetDataTable
have to be asynchronous as well?
public DataTable GetDataTable(string connectionString, string cmdText)
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString)) {
using (SqlCommand comm = new SqlCommand(cmdText, conn)) {
conn.Open();
dt.Load(comm.ExecuteReader);
return dt;
}
}
}
private async void Button1_Click(object sender, EventArgs e)
{
try {
statusLabel.Text = "Processing...";
Task<DataTable> dtTask = Task.Run(() => GetDataTable(connectionString, commandText));
await dtTask;
myDataTable = dtTask.Result;
statusLabel.Text = "Done!";
} catch (Exception ex) {
MessageBox.Show("Error");
}
}
UPDATE
I managed to do solve this problem by making GetDataTable()
return a Task
of DataTable
and changing both .Open
and .ExecuteReader
to their asynchronous counterparts. For the other method, those three lines inside the Try
block I reduced to one:
myDataTable = await GetDataTable(connectionString, commandText);
Thanks to everyone's patiences!