I have to apply for 2 approches:
- handle each HTTP request with a different thread/task.
- finish the requests gracefully when the cancellation token invoked.
Now, I have a problem that when the cancellation token invoked and a request doesn't arrive - I stack in the "server.getContext" blocking area. Any idea how can I solve it?
public void Listen()
{
CancellationTokenSource source = new CancellationTokenSource();
CancellationToken token = source.Token;
server.Start();
Console.WriteLine($"Waiting for connections on {url}");
HandleShutdownWhenKeyPressed(source);
HandleIncomingHTTPRequests(token);
server.Close();
}
void HandleIncomingHTTPRequests(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
HttpListenerContext ctx = server.GetContext();
// I stack here until the request has arrived even if the cancellation token has invoked.
Task.Run(() =>
{
HttpListenerRequest req = ctx.Request;
HttpListenerResponse res = ctx.Response;
// SOME STUFF ....
},token)
}
}
Thanks in advance.