I am learning async await and implementing in my old asp.net. I am using c# 4.6.
Now the page is always running synchronously after adding async-await. It's waiting for the api to send back result and then shows the message on screen.
What I am looking for is that the page kicks off a thread and be responsive(I can do other bits on it). When it's completed, it shows the result.
Below is my button click, HTTP call (which will initiate the async req) and API method .
I have
- Followed the examples https://msdn.microsoft.com/en-us/library/hh191443.aspx
- Looked for solution on StackOverflow and other forums. I believe I am doing it the same way (which of course I am not :( ).
Added Async="true" on aspx page.
Button Click
protected async void btnCopy_Click(object sender, EventArgs e)
{
await RunAsync(Guid.Parse(SourceBusinessID), Guid.Parse(DestinationBusinessID), false);
if (lblError.Text == "")
{
lblError.Text = "Copy Completed!";
}
}
public async Task RunAsync( Guid SourceBusinessID, Guid DestinationBusinessID,bool copyAdviser)
{
using (var client = new HttpClient())
{
var request = new HttpRequestMessage()
{
RequestUri = new Uri("http://localhost:52140/api/DummyAccounts/"),
Method = HttpMethod.Get,
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
client.Timeout = TimeSpan.FromSeconds(500);
var response = await client.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
lblError.Text = response.StatusCode.ToString();
}
}
}
API
public IHttpActionResult Get(Guid sourceBusinessID, Guid destinationBusinessID,bool copyAdviser = true)
{
try
{
CopyHelper.SourceBusinessID = sourceBusinessID;
CopyHelper.DestinationBusinessID = destinationBusinessID;
CopyHelper.CopyAdviser = copyAdviser;
logger.Info("Copy buisness started:" + DateTime.Now);
bool status = CopyBusinessService.CopyBusiness(CopyHelper.SourceBusinessID, CopyHelper.DestinationBusinessID, CopyHelper.CopyAdviser);
if (status)
{
logger.Info("Copy business finished:" + DateTime.Now);
return Ok(true);
}
else
{
logger.Info("Copy business failed:" + DateTime.Now);
return Ok(false);
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
Any help will be much appreciated.