Question

IHttpAsyncHandler means run the request asynchronously.

Using the thread pool also can run asynchronously.

So if I want to implement a function (like Comet,long poll), between using thread pool with IHttpHandler and using IHttpAsyncHandler, which is better?

EDIT: @Jon Skeet: Thank you for your patient reply. Let me make a conclusion. If I use delegate.BeginInvoke in the IHttpHandler,the 'Main Thread' of processing request still keeps spinning until the request end,no matter what happened with the pooled thread. If I use the IHttpAsyncHandler, the 'Main Thread' of processing request will call the BeginProcessRequest and after that,it will be released (to process other request). The BeginProcessRequest method will do something asynchronously. When the asynchronous action finished,the EndProcessRequest method will be called.(or we can say the 'Main Thread' will call the EndProcessRequest function to finished current request)

All above are what I think, is it right?

Was it helpful?

Solution

The difference is that with a truly asynchronous model, you don't need a thread per request at all. If you have a thread per request, whether or not it's on the thread pool, you'll be stuck handling a large number of connections (as you need to for things like long polling).

Suppose you have a hundred thousand clients, each long-polling - do you really want 100,000 threads? (Hint: I doubt that you've got enough memory...)

With genuine asynchrony, you can react to events by ending a request without having a dedicated thread per request. Note that with C# 5 and .NET 4.5, there are simpler ways than using IHttpAsyncHandler, too. It depends on what you're trying to achieve, but both WCF and MVC have async-oriented approaches where you can write an async method, using await expressions etc. If you then await something which doesn't in itself take a thread (e.g. a timer, or perhaps some IO completing) then you can manage a huge number of concurrent connections.

EDIT: To respond to your further questions: yes, if you use just IHttpHandler, the request must be completed when the ProcessRequest call completes. You can't just leave it "dangling"... whereas IHttpAsyncHandler allows the request to still be in progress until EndProcessRequest is called. Don't forget that this is a very old interface though - it's not terribly clearly documented, and I wouldn't suggest using it these days, when there are significantly better approaches to asynchrony, particularly using .NET 4.5 and C# 5. But the main point of being able to have a request in progress but without any specific thread being associated with it still holds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top