CancellationToken when request gets aborted #21
-
Hi, is there any |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 7 replies
-
Hello. Unfortunately, there is no way to know if the connection was closed by the client until you try to write or read something. It's a current limitation of the HttpListener in the .NET Core implementation. Before, in the .NET Framework, there was a method called RegisterForDisconnectNotification that, through reflection, would make it possible to obtain a token for client disconnection, but apparently it was removed in the new implementations of .NET. The client can disconnect and the internal stream continue active. As I mentioned, it's only possible to know if the client disconnected if you try to write or read that stream. Perhaps when the Cadente is set as the HTTP engine of Sisk, it will be possible to do this, because we will have access to the socket in its entirety, but for now, I don't know a way to make something that works this way on Windows, Linux, and OSX. |
Beta Was this translation helpful? Give feedback.
-
Update on this: Sisk 1.5.0 beta 3 now supports a very experimental request disconnect token. Basically, it listens to the TCP interfaces of the current operating system and creates a CancellationToken through pooling for that interface, listening for when the connection is no longer "Established". What happens in the end is that, when a connection is aborted or disconnected, this state changes, alters the result of the CancellationToken and fires the disconnection event. Example: static void Main(string[] args)
{
using var host = HttpServer.CreateBuilder(55665)
.UseConfiguration(config =>
{
config.ThrowExceptions = true;
})
.UseRouter(router =>
{
router.SetRoute(RouteMethod.Get, "/long-task", async (HttpRequest req) =>
{
Console.WriteLine("Long running request...");
var cancellation = req.DisconnectToken;
for (int i = 0; i < 1_000; i++)
{
if (cancellation.IsCancellationRequested)
{
Console.WriteLine("Request aborted!");
break;
}
await Task.Delay(1000);
}
return new HttpResponse();
});
})
.Build();
host.Start();
} Currently I did it by pooling, but I'm looking for more performant ways to do this. Contributions and tests are welcome! |
Beta Was this translation helpful? Give feedback.
Hello.
Unfortunately, there is no way to know if the connection was closed by the client until you try to write or read something. It's a current limitation of the HttpListener in the .NET Core implementation. Before, in the .NET Framework, there was a method called RegisterForDisconnectNotification that, through reflection, would make it possible to obtain a token for client disconnection, but apparently it was removed in the new implementations of .NET.
The client can disconnect and the internal stream continue active. As I mentioned, it's only possible to know if the client disconnected if you try to write or read that stream. Perhaps when the Cadente is set as the HTTP engine of Sisk,…