Skip to content
This repository was archived by the owner on Dec 18, 2018. It is now read-only.
This repository was 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

Description

@markvincze

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.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions