Friday, July 15, 2011

C# await for WaitHandle

The async CTP that adds the C# await keyword doesn’t include an awaitable WaitHandle.  It’s easy to add yourself.  Just copy and paste the following code somewhere in your project and you’ll have an awaitable WaitHandle.

Warning: don't use this on AutoResetEvents, or the behavior may not be what you expect.

2 comments:

  1. Why don't AutoResetEvent's work, and what could be done to fix them? This is a great start, but I use AutoResetEvents pretty heavily.

    ReplyDelete
  2. AutoResetEvent would "work", depending on how you use them. But some of what makes them special is lost, which is why it's recommended to not use them with this technique.
    Specifically, AutoResetEvent's have a special characteristic that you can do a WaitAll on handles that include AutoResetEvents but none of them are reset by the waiter unless *all* handles are signaled at once. But when you do the equivalent with Task.WhenAll, the events are reset independently as soon as they are signaled. And if the WhenAll is never satisfied, the events were still reset.
    There may be other scenarios that I'm not thinking of.

    ReplyDelete