ASP.NET (C#) Question

Async taking 15x longer than sync

I'm comparing the performance when taking away

await
keyword from my method, and it's giving me over 15x better performance.

The following method performs much better:

private static async Task<HttpResponseMessage> AwaitResponse(HttpRequest proxy)
{
foreach (var header in proxy.Request.Headers)
{
Client.Instance.DefaultRequestHeaders.Add(header.Key, header.Value);
}

var response = Client.Instance.SendAsync(proxy.Request).Result;
return response;
}


than this one:

private static async Task<HttpResponseMessage> AwaitResponse(HttpRequest proxy)
{
foreach (var header in proxy.Request.Headers)
{
Client.Instance.DefaultRequestHeaders.Add(header.Key, header.Value);
}

var response = Client.Instance.SendAsync(proxy.Request);
return await response;
}


Notice How I am calling .Result in the first version of the method.

Why is this happening? Why is there such a tremendous performance penalty?

Please note that
Client
is simply a static instance of
HttpClient
.

Answer Source

When using await, the execution context of the code is suspended until the async method returns. By default, await attempts to restore the new thread to the incoming synchronization context that it originated in. This can sometimes have performance implications, as the CLR needs to wait for the original SynchronizationContext to marshal back.

Generally speaking, unless you have a specific need to return to the same thread context that you left (say, in a client app, to return to the UI thread), it's best to add ConfigureAwait(false) and continue on any arbitrary thread.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download