Tip 3: Wrap events up in Task-returning APIs and await them
- Posted: Mar 12, 2013 at 6:00 AM
- 39,419 Views
- 18 Comments
Loading User Information from Channel 9
Something went wrong getting user information from Channel 9
Loading User Information from MSDN
Something went wrong getting user information from MSDN
Loading Visual Studio Achievements
Something went wrong getting the Visual Studio Achievements
Right click “Save as…”
Async Tip #3: You can wrap events up in Task-returning APIs and await them. This can dramatically simplify code.
Slides and source code are available on Lucian's blog.
This video introduces a new pattern for dealing with events: you can await them! Now why would you want to do that? Well, in some cases like responding to a button-click, it's fine to handle events in the way that you always have with top-level event handlers. But if you're building a complicated UI that has to orchestrate a whole load of events (StoryboardCompleted, MediaElementCompleted, PointerMoved, PointerReleased, ...) then it makes for cleaner code to await them. The key is the type TaskCompletionSource introduced in .NET4.