Async WebApi ActionFilterAttribute. The asynchronous module or handler has completed while the asynchronous operation has not yet completed

I understand what is waiting for the task to complete (expected). But I'm confused by what it really means.

Code that doesn't work :

public async override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
    if (actionExecutedContext.Response.Content != null)
    {
        var responseContent = await actionExecutedContext.Response.Content.ReadAsStringAsync();
        DoSomething(responseContent);
    }
}

The code works :

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
    if (actionExecutedContext.Response.Content != null)
    {
        var responseContent = actionExecutedContext.Response.Content.ReadAsStringAsync().ContinueWith(
        task =>
        {
            DoSomething(task.Result);
        });
    }
}

Obviously, the error message The asynchronous module or handler has completed while the asynchronous operation is still waiting. tells me that there were no expectations of the completion of the asynchronous call, but instead the "main" thread continued. I was expecting the stream to continue, but not in the current method. I thought the thread would return to the asp.net stack, do some other work, and return after the asyncOperation () operation was completed.

(, -) - . , IActionFilterAttribute -. -, , , .

-, , ? , .

+5
2

, void, , . . void ?.

/ , . ActionFilterAttribute , IHttpActionFilter, IActionFilter (ExecuteActionFilterAsync). , , Attribute.

:

public class AsyncActionFilterAttribute : Attribute, IActionFilter
{
    public async Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
    {
        HttpResponseMessage response = await continuation();
        DoSomething(response);
        return response;
    }
}
+6

public async override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)

OnActionExecuted :

public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)

, , , .

, .

0

All Articles