It looks to me like you'll end up with a bifurcation of listeners. Within ProcessAsync
, you start a new task to listen (via Task.Factory.StartNew), and then you call ProcessAsync
again at the end of the method. How can that ever finish? It's not clear whether that's the cause of your performance problems, but it definitely looks like an issue in general.
I'd suggest changing your code to be just a simple loop:
static async Task ProcessAsync(HttpListener listener) {
while (KeepGoing) {
var context = await listener.GetContextAsync();
HandleRequestAsync(context);
}
}
static async Task HandleRequestAsync(HttpListenerContext context) {
// Do processing here, possibly affecting KeepGoing to make the
// server shut down.
}
Now currently the above code ignores the return value of HandleRequestAsync
. You may want to keep a list of the "currently in flight" tasks, and when you've been asked to shut down, use await Task.WhenAll(inFlightTasks)
to avoid bringing the server down too quickly.
Also note that Thread.Sleep
is a blocking delay. An asynchronous delay would be await Task.Delay(1000)
.