How to Await Just About Anything
Lucian Wischik is publishing a series of blog posts showing how Await can be used in a wide variety of situations ranging from awaiting an animation to complete to capturing the results of a command line program.
The basic pattern can be seen in his post titled How to await a storyboard. At the core is the TaskCompletionSource. When the storyboard fires its completed event, the attached event handler uses the TaskCompletionSource to pass the result to the Task.
This allows for the syntax “Await storyboard1.PlayAsync()”. If you want it even shorter, just “Await storyboard1” you can build an extension method called GetAwaiter and have it return a TaskAwaiter. The compiler will look for a method with this name and rewrite your code accordingly.
For a more complex example of this event-handler based approach see How to await a MediaElement. This one creates two functions, OpenAsync and PlayAsync, and discusses how error handling can be supported in a clean fashion.
Lucian’s RunCommandLineAsync supports reading both the standard output and standard error streams from a command line program. Doing this is not as easy as it might seem at first due to the interaction of the aforementioned streams and the input stream. Lucian explains how multiple tasks are used for this,
> The precise way that “RedirectStandardInput/Output/Error” will work depends on the internal details of the process we’re launching. All we can say with any certainty is that (1) the process might not finish until we close its StandardInput; (2) we might have to read data from StandardOutput/StandardError before we can write any more data into StandardInput; (3) we might have to write more data into StandardInput before we can read more data from StandardOutput/StandardError. Those constraints imply that the three tasks “tin/tout/terr” must all be launched concurrently, and then awaited using Task.WhenAll().
For more on how Await and GetAwaiter interact in the compiler, see Stephen Toub’s article titled await anything.
Yoni Goldberg Oct 30, 2014
Dmytro Svarytsevych Oct 30, 2014