tpeczek/Lib.AspNetCore.ServerSentEvents

How to rapidly close SSE connections?

drittich opened this issue · 4 comments

I'm using SSE in a web application hosted by a Windows Service. I noticed when I stop the service that it takes a long time (I assume due to the SSE connections that are open?) If I remove the SSE code the service will stop immediately.

I have tried running the following code in the StopAsync event of the service, but does not seem to make shutdown any faster:

var clients = _serverSentEventsService.GetClients();
foreach (var client in clients)
{
	client.Disconnect();
}

but it makes no difference. Is there a way to do a rapid shutdown of SSE?

Hi @drittich,

My apologies, somehow I missed this earlier. Sadly disconnecting a client when it comes to SSE isn't a straightforward subject due to auto reconnects on client side. There are some preconditions which has to be met for the Disconnect method to achieve the desired result: https://tpeczek.github.io/Lib.AspNetCore.ServerSentEvents/articles/disconneting-clients.html.

And even when used properly, there will be a delay in stopping the service as majority of clients will still attempt to reconnect at least once.

Thanks for the response. I suppose there is no way to force a dispose of the ServerSentEventsService and have that immediately break all connections?

No there is nothing like that, but if you want to be brutal you can try grabbing IHostApplicationLifetime and calling StopApplication which in theory should kill the ASP.NET Core hosting. I'm not able to tell how would that behave as I've never tried it.

Thanks, I will try that. My application is a little unusual in that it is a localhost website hosted in a Windows Service, so when the service is shutting down I no longer care about the client, which will be the same machine 99.9% of the time.