HttpListener: chances of missing a message using while loop and BeginGetContext

27 Views Asked by At

I'm afraid that there is space between one BeginGetContext and the next for a message to fly by unnoticed. Is that so?
Can receiving many requests simultaneously result into some of them being ignored?

Task.Run(() => {
    while (Not(CTok.IsCancellationRequested) && listener.IsListening) {
        IAsyncResult result = listener.BeginGetContext(new AsyncCallback(DoWork), listener);
        result.AsyncWaitHandle.WaitOne();
    }
});
private void DoWork(IAsyncResult willResult) {
   HttpListener listener = (HttpListener)willResult.AsyncState!;

   // Call EndGetContext to complete the asynchronous operation.
   HttpListenerContext context = listener.EndGetContext(willResult);
   
   //do the actual work here, like parsing the content and building a response
}

It's the first time I'm using this AsyncCallback/IAsyncResult pattern, as well as using HttpListener,

On a separate note: if i run multiple listeners with prefixes that make them able to handle the same uri (http://*.foo.com/ and http:/*.com/) will just one run it's AsyncCallback or will both try to respond?

-EDIT-
switched to await/async, as it is available.

Task.Run(async () => {
    while (!(CTok.IsCancellationRequested) && StartedHttpListener.IsListening) {
    var ctx = await StartedHttpListener.GetContextAsync();
    _ = Task.Run(()=>Handler(ctx,CTok), CTok);
    //brief moment where no Context is being awaited/listened to, before the next loop iteration takes place
}

Is there any chance that this loop will miss a message, if multiple ones are received at the same time?

-ANSWER- by Panagiotis Kanavos
"..No request will be lost. Subsequent requests will wait until the iteration completes. .."

0

There are 0 best solutions below