Skip to content
This repository has been archived by the owner on Dec 18, 2018. It is now read-only.

"Error -4081 ECANCELED operation canceled" when closing the connection of a text/event-stream #1402

Closed
markvincze opened this issue Feb 26, 2017 · 1 comment

Comments

@markvincze
Copy link

I'm trying to implement an event-stream using a middleware with the following code (somewhat simplified):

public class MyEventStreamMiddleware
{
    public MyEventStreamMiddleware(RequestDelegate next)
    {
    }

    public async Task Invoke(HttpContext context)
    {
        var response = context.Response;
        response.Headers.Add("Cache-Control", "no-cache");
        response.Headers.Add("Expires", "-1");
        response.Headers.Add("Pragma", "no-cache");

        response.ContentType = "text/event-stream";

        try
        {
            while(true)
            {
                if (context.RequestAborted.IsCancellationRequested)
                {
                    break;
                }

                await WritePing(response.Body, context.RequestAborted).ConfigureAwait(false);

                await Task.Delay(1000, context.RequestAborted).ConfigureAwait(false);
            }
        }
        catch(TaskCanceledException)
        {
            // This just means the connection was closed.
        }
    }

    private async Task WritePing(Stream stream, CancellationToken ct)
    {
        byte[] buffer = Encoding.UTF8.GetBytes("ping");
        await stream.WriteAsync(buffer, 0, buffer.Length, ct).ConfigureAwait(false);
        await stream.FlushAsync(ct).ConfigureAwait(false);
    }
}

The stream itself works properly, for example if I open it in the browser. But when I close the browser tab, after a couple of seconds I see the following error printed to the terminal:

info: Microsoft.AspNetCore.Server.Kestrel[14]
      Connection id "0HL2U89M7EHTU" communication error.
Microsoft.AspNetCore.Server.Kestrel.Internal.Networking.UvException: Error -4081 ECANCELED operation canceled

Is this just some debug message left in, or am I doing something genuinely wrong, and this could cause issues on production? (For example I'm not 100% sure I'm using context.RequestAborted the right way.)

@halter73
Copy link
Member

Today RequestAborted will not fire for graceful FINs from the client. The logic was that the request isn't exactly aborted in that case, but this will change in 2.0.0 to work the way you expected.

In 2.0.0, RequestAborted will fire whenever the connection ends for any reason assuming that the middleware is still executing at the time the connection closes of course.

The error should be pretty benign. Unfortunately there's not really much you can do to avoid it in the meantime.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants