0

I have a custom ASP.NET Web API message handler that for each request that comes it will save the request method and request uri to a custom database:

I'm trying to run the Save method async and I have done this so far. I just want to know if this is the right way to call Save method asynchronously? Is it correct to have await before Task.Run... ? Should I also add async on my save method: private async void Save(

Can somebody tell if I can use instead TaskCompletionSource<T>()

public class CustomHandler : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
        CancellationToken cancellationToken)
    {            
        var response = await base.SendAsync(request, cancellationToken);         

        await Task.Run(() => Save(request), cancellationToken);

        return response;
    }

    private void Save(HttpRequestMessage request)
    {            
        var method = request.Method.Method;
        var url = request.RequestUri.ToString();

        // here is saved to custom db code removed
        ............................

    }
}

1 Answer 1

2

I recommend you read my async intro post.

I just want to know if this is the right way to call Save method asynchronously?

If this were a UI application, await Task.Run would be acceptable but not ideal. However, since this is an ASP.NET application, await Task.Run is not good at all.

On the server side, you should avoid Task.Run or anything else that queues work to the thread pool.

Should I also add async on my save method?

A method should only be async if it uses the await keyword.

If your database supports asynchronous methods (e.g., EF6), then you can use those in your Save method, which would require it to be marked async (and should be returning Task). Then you could call it as such:

private async Task SaveAsync(HttpRequestMessage request);
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{            
    var response = await base.SendAsync(request, cancellationToken);         
    await SaveAsync(request);
    return response;
}

However, if your database does not support async, then you should just call it synchronously:

private void Save(HttpRequestMessage request);
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{            
    var response = await base.SendAsync(request, cancellationToken);         
    Save(request);
    return response;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.