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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s