Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire and forget using ThreadPool.QueueUserWorkItem or async await? [closed]

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);
        }
    }
like image 716
MoXplod Avatar asked Jun 26 '14 18:06

MoXplod


1 Answers

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.

like image 94
Stephen Cleary Avatar answered Oct 16 '22 03:10

Stephen Cleary