I have the two following methods, which i am using to do fire and forget calls to http urls. Initially i was using ThreadPool.QueueUserWorkItem, but was recommended to use Async Await, due to concerns of thread exhaustion, as this method might be called frequently.
First question is which one is better?
Second question - is the async await implementation correct? As i debug through it, it seems to be synchronous, which is a big problem, as i need it to free up the calling asp.net thread and to return response back to user without waiting for the http call to complete.
Call -
Send("http://example.com");
Method-
public static void Send(string url)
{
ThreadPool.QueueUserWorkItem(
o =>
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = false;
request.Timeout = 5000;
var response = request.GetResponse();
response.Close();
}
catch (Exception ex)
{
SendException(ex, url);
}
});
}
ASYNC/ AWAIT -
Call -
await SendAsync("http://example.com");
Method -
public async static Task SendAsync(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = false;
request.Timeout = 5000;
var response = await request.GetResponseAsync().ConfigureAwait(false);
response.Close();
}
catch (Exception ex)
{
SendException(ex, url);
}
}
First question is which one is better?
Neither. I recommend you at least register the work with the ASP.NET runtime using something like HostingEnvironment.QueueBackgroundWorkItem
; I describe this and other approaches on my blog.
Second question - is the async await implementation correct? As i debug through it, it seems to be synchronous
It's asynchronous, but you're awaiting it. This tells ASP.NET to not complete its response until that work is done. So, it's not "fire and forget".
i need it to free up the calling asp.net thread and to return response back to user without waiting for the http call to complete.
As currently written, it is freeing up the thread but delays returning the response until the HTTP call is completed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With