Avik Das
Avik Das

Reputation: 121

How to correctly await on lambda Func delegate C#

I am confused on the correct way to use the pass the lambda to func delegate for the httpClient.

E.g. The Call is a generic function where there is an await on the TaskFunctor function delegate.

What should be the correct way to pass a HttpClient in lamda function for the taskFunctor so it can await for the response ?

private async Task<HttpResponseMessage> Call(string operationId, Func<Task<HttpResponseMessage>> taskFunctor)
        {
            HttpResponseMessage response = null;
            try
            {
                response = await taskFunctor();
                s_tracer.Trace(0, "Got response for {0}: {1}", operationId, response.StatusCode);
            }
            catch (Exception ex)
            {
                s_tracer.Trace(0, "Got response for {0}: {1}", operationId, ex.Message);
            }

            return response;
        }

What is the correct way for the make pass lambda ?

public async Task<HttpResponseMessage> GetAsync2(string requestUri)
        {
            string absoluteRequestUri = requestUri;
            HttpClient httpClient = new HttpClient();

            HttpResponseMessage response = await Call(
                string.Format("HttpClientFacade:Get {0}", requestUri),
                async() => await httpClient.GetAsync(requestUri)); <<<<<<ASYNC Lamda

            return response;
        }

OR

 public async Task<HttpResponseMessage> GetAsync1(string requestUri)
        {
            string absoluteRequestUri = requestUri;
            HttpClient httpClient = new HttpClient();

            HttpResponseMessage response = await Call(
                string.Format("HttpClientFacade:Get {0}", requestUri),
                () => httpClient.GetAsync(requestUri));  <<<<<<Lamda

            return response;
        }  

Upvotes: 0

Views: 237

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456477

In this case, they're practically the same. For trivial lambdas, feel free to elide async and await. However, if your lambda does anything non-trivial (i.e., anything that could cause exceptions, or any using statements), then you should keep the async/await in.

Removing the async/await gives you an immeasurably small performance benefit, but the code is more likely to remain correct over time if you leave them in.

Upvotes: 4

Related Questions