Poul K. Sørensen
Poul K. Sørensen

Reputation: 17540

Can I return a Task directly with HttpResponseMessage, such no async declaration is needed

I have the following WebAPI action and is wondering if returning Task<bool> and return _store.ContainerExistsAsync(container) directly is better;

I ask because, if I understand async/await correctly, the compiler creates a statemachine at the await to return to the same state. Returning the task directly without having to await it in the action, would that be theoretical faster?

    public async Task<HttpResponseMessage> GetContainer(string container)
    {
        if (container.Length < 3 ||
            container.Length > 63 ||
            !Regex.IsMatch(container, @"^[a-z0-9]+(-[a-z0-9]+)*$"))
            return Request.CreateResponse(HttpStatusCode.BadRequest, new { errors = new string[1] { "Container Name is not alowed." } })            

        return Request.CreateResponse<bool>(HttpStatusCode.OK, await _store.ContainerExistsAsync(container));

    }

Upvotes: 1

Views: 374

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456917

Yes, if you can implement an asynchronous method without async and await, then go ahead; async/await will add overhead.

This is commonly seen when the last line of a method has the only await and looks like return await ...;

In your particular example, I'm not 100% sure whether this would work since the method is doing something after the await.

It's easy enough to make it return the Task<bool> from ContainerExistsAsync directly, but the error handling would also need to change. If throwing a HttpResponseException works well enough, then yes, you would be able to implement an asynchronous method without using async.

Upvotes: 1

Related Questions