Queueing items to ThreadPool

The simplicity of this approach is astonishing. And it was in .net since .net 4, but our eyes are not always looking in the direction we should.

ThreadPool.QueueUserWorkItem

The method is offering overload with Action delegate and argument. Actually the argument is significant. If it is blocking function it will Queue the new action only when it stops blocking.

Thus the simple http server can only be:

while(true) {
   ThreadPool.QueueUserWorkItem(Process, listener.GetContext());    
 }

void Process(object o)
 {    var context = o as HttpListenerContext;
    // process request and make response
}

We are waiting until someone connects. And yes it only processes maximally pool-size amount of concurrent connections. But that is another story I think. I wanted to share the beauty of this solution.

Inspiration was from
https://codehosting.net/blog/BlogEngine/post/Simple-C-Web-Server
https://stackoverflow.com/questions/9034721/handling-multiple-requests-with-c-sharp-httplistener