Professor of programming
Professor of programming

Reputation: 3093

Asynchronous OWIN pipeline

I'm using ASP.NET 5 (core) and the OWIN pipeline. I can see many examples of how to output a response, ie:

http://odetocode.com/blogs/scott/archive/2013/11/11/writing-owin-middleware.aspx

However, if you take the following:

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.Run(context =>
        {
            MvcHandler mvcHandler = new MvcHandler();
            return mvcHandler.ProcessRequest(context);
        });
    }
}

public class MvcHandler
{
    public Task ProcessRequest(HttpContext context)
    {
        return Task.Run(() => ProcessRequestInternal(context));
    }

    private void ProcessRequestInternal(HttpContext context)
    {
        context.Response.WriteAsync("Hello world!");
    }
}

If the above code is executed, because ProcessRequestInternal isn't asynchronous, will the requests still be responded to asynchronously or will the requests be responded to one after the other?

Upvotes: 1

Views: 1425

Answers (1)

Markus Jarderot
Markus Jarderot

Reputation: 89241

The WriteAsync is asynchronous, and is called in a non-async context. This will orphan the returned task.

You can either return the task, or wait for it.

private Task ProcessRequestInternal(HttpContext context)
{
    return context.Response.WriteAsync("Hello world!");
}

or

private void ProcessRequestInternal(HttpContext context)
{
    context.Response.WriteAsync("Hello world!").Wait();
}

Better would be to propagate the async context:

private async Task ProcessRequestInternal(HttpContext context)
{
    await context.Response.WriteAsync("Hello world!");
}

Upvotes: 1

Related Questions