I built a windows forms application, which sends data (using a POST call) to a web service on a button click event. In production, sometimes the users are seeing the "Server Busy" message box (as below).
I am using Async Await pattern to post messages to the service. Below is my code snippet:
private void button1_Click(object sender, EventArgs e)
{
SendDataToHost();
}
private async void SendDataToHost()
{
//Get the data which needs to be sent to the host..
var result= await PostData(data);
//If the service fails to process this data for any reason, then
// it returns the result object with succeeded as false
if (result != null && !result.Succeeded)
{
MessageBox.Show("Failed");
}
else
{
MessageBox.Show("Success");
}
}
public async Task<Result> PostData(Data data)
{
Result result = await PostAsync("cases", data);
return result;
}
I understand the "Server busy" message box is being populated because the UI thread is being blocked. But what I am trying to understand is, the purpose of using Async and Await is to keep the UI responsive, but why is the UI thread blocked?
Also, I researched online and I found some solutions, but I want to completely understand if they will fix the issue? As it is a production issue and I am not able to reproduce in dev environment and I want to be sure that the change will fix the issue.
The 2 options I found are:
1) To use ConfigureWait(false)
. From my understanding, this will make sure the "POST" call does not happen in UI context.
public async Task<Result> PostData(Data data)
{
Result result = await PostAsync("cases",data).ConfigureAwait(false);
return result;
}
2) Call the Post Method in a new Task and await on the Task.
private async void SendDataToHost()
{
//Get the data which needs to be sent to the host..
**var result= await Task.Run(()=>PostData(data));**
//If the service fails to process this data for any reason, then
// it returns the result object with succeeded as false
if (result != null && !result.Succeeded)
{
MessageBox.Show("Failed");
}
else
{
MessageBox.Show("Success");
}
}
I would like to know if I am heading in the right direction to solve this issue or are there any other options I need to explore?