I'm fairly new to async/await and I'm having difficulties with a task that is not completing before the form closes. It works fine most of the time, but occasionally there are instances where I need to retrieve a dataset or modify a table, and the query is too slow to complete before the UI thread closes.
I could use Task.Wait(), or use ExecuteNonQuery() instead of ExecuteNonQueryAsync() but I want to avoid deadlocks before the form closes. I've searched around on a few other posts, but I'm still a little iffy on what the best approach may be.
The example below is updating a support call's status before closing the form.
private async void frmSupportDetails_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
// Sets call to incomplete if it was pending/transferred
if (status != "Complete" && status != "Incomplete")
{
dbQuery = "UPDATE SupportCalls SET [Status] = @status, [CompletedNote] = @completedNote WHERE CallNum = @callNum";
await sql.executeAsync(dbQuery, new OleDbParameter("@status", "Incomplete"), new OleDbParameter("@completedNote", txtCompletedNote.Text), new OleDbParameter("@callNum", ProgOps.selectedCallNum));
}
// Asks to log callback date
if (promptCallBack == true)
{
DialogResult callbackOption = MessageBox.Show("Would you like to log that you are returning the customer's call?", "Callback Date", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
if (callbackOption == DialogResult.Yes)
{
dbQuery = "UPDATE SupportCalls SET CallbackDate = Now() WHERE CallNum = @callNum";
await sql.executeAsync(dbQuery, new OleDbParameter("@callNum", ProgOps.selectedCallNum));
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error Occurred - frmClose()", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
public async Task executeAsync(string dbQuery, params OleDbParameter[] parameters)
{
using (var dbConn = new OleDbConnection(CONNECT_STRING))
using (var dbComm = new OleDbCommand(dbQuery, dbConn))
{
if (parameters != null)
dbComm.Parameters.AddRange(parameters);
await dbConn.OpenAsync().ConfigureAwait(false);
await dbComm.ExecuteNonQueryAsync().ConfigureAwait(false);
}
}