Search code examples
c#async-awaitmanualresetevent

await any async method and (event or boolean)


I have this code :

ManualResetEvent EventListenerStopped;
...
while (true)
{
    IAsyncResult iar = this.ListenerHttp.BeginGetContext(ProcessRequest, null);
    if (WaitHandle.WaitAny(new[] { this.EventListenerStopped, iar.AsyncWaitHandle }) == 0)
        return;
}

Basically it waits for any of two events :

  • if a request is received, it processes it and wait for the next one.
  • if EventListenerStopped is raised, it exits the loop.

This code has been running in production beautifully for quite some time now.

I wanted to try and convert it to the new await/async mechanism and can't seem to find a good simple way to do it.

I tried with a boolean the caller can turn to false. It obviously does not work as it exits the loop only after a new request has been received and processed :

bool RunLoop;
...
while (this.RunLoop)
{
    HttpListenerContext listenerContext = await this.ListenerHttp.GetContextAsync();
    ProcessRequest(listenerContext);
}

I'm wondering if it's even possible to rewrite my simple old-style loop with async/await. If yes, would someone be willing to show me how ?


Solution

  • It's not specific to async-await, but you're probably looking for CancellationToken (which is used with a lot of async-await code anyway):

    http://blogs.msdn.com/b/pfxteam/archive/2009/05/22/9635790.aspx

    The 'BlockingOperation' example code seems similar to what you're trying to do:

    void BlockingOperation(CancellationToken token) 
    { 
       ManualResetEvent mre = new ManualResetEvent(false); 
       //register a callback that will set the MRE 
       CancellationTokenRegistration registration = 
          token.Register(() => mre.Set()); 
       using (registration) 
       { 
          mre.WaitOne(); 
          if (token.IsCancellationRequested) //did cancellation wake us? 
              throw new OperationCanceledException(token); 
       } //dispose the registration, which performs the deregisteration. 
    }