How should I implement the C# server side portion of long-polling for ajax requests?
I've got an architecture that involves browsers polling via ajax every 3 seconds for updates and I'd like to change that to long-polling.
I'd like to have 1, 2.. {n} clients long-polling, waiting for updates and have something happen on the server to signal the waiting clients to return. My first thought was to use an EventWaitHandle
, and I can do this easily if I just want to support 1 client. I'd just have an AutoResetEvent
WaitHandle
that would WaitOne
to block the client, maybe with a timeout, maybe not. Either way, an AutoResetEvent
will only allow me to support 1 client (since it only wakes 1 waiting thread) and I want n clients.
I'm pretty sure I need to use a ManualResetEvent
WaitHandle
, but I'm not sure when to call Reset
after I Set
it (when waking the threads). Should I simply Thread.Sleep
some arbitrary amount in between the Set
and Reset
?
In psuedo code, the waking logic would be
- get
ManualResetEventWaitHandle
- call
Set
- ensure all waiting clients have woken, while preventing new requests from blowing through
- call
Reset
now that all waiting clients have received their updates
Its that 3rd line that i'm having a hard time with. Currently I am tossing around the idea of having a LastTxID
that the client / server maintain and potentially using 2 wait handles. However, before I went crazy with this implementation I wanted to get feedback here to see how they would implement the waking logic.
Edit: assume I've got the problems associated wit开发者_运维百科h having max concurrent users figured out, either by tweaking IIS or hosting via WCF or some other solution. I only want to focus on the waking logic.
One idea, in pseudo code
- Maintain a thread-safe list of connection id's, possibly use the session id
- Give every connection its own AutoResetEventWaitHandle
- In a thread safe manner, loop through those wait handles and set them when there is an update
- on session end, in a thread safe manner, remove that connection / session id from the list
I'd love to get some feedback on this
con's to this approach
- have to maintain a list of connections
- have to generate {n} wait handles for {n} clients
精彩评论