According to the HttpListener reference, a call to HttpListener.GetContext will block until it gets a HTTP request from a client.
I wonder if I can specify a timeout so that after the timeout the function will return. I think otherwise it's unreasonable, since you cannot guarantee there will be a request to make this function return, then how can one terminate this call?
P.S. I know there is a async version of it (BeginGetContext) BUT the problem remains because the corresponding EndGetContext will block until an HTTP request arrives.
So as a result, there will be always one thread (if you do it multi-threaded) cannot return because it's blocked on waiting for a request.
Am I missing anything?
UPDATE:
I found this link to be useful. I also found that calling HttpListener.Close() actually terminates the waiting threads that created by the BeginGetContext()s. Somehow HttpListener.Close() fires the callbacks that BeginGetContext() registered. So before you do a HttpListener.EndGetContext(), do check if HttpListener has stopped.
The callback that invokes EndGetContext should never be called unless an HTTP request has already arrived, or the listener has failed (in which case EndGetContext will throw an exception). Thus, it will not block if used properly.
BeginGetContext and EndGetContext--that is, asynchronous operations--are what you want.
Begin and End methods work such that Begin says "signal me when X is ready," and End says "give me that X about which you just signaled me." Naturally, the latter will block in theory, but will return instantaneously.