BT

How to Await Just About Anything

by Jonathan Allen on Dec 18, 2012 |

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.

Hello stranger!

You need to Register an InfoQ account or to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Tell us what you think

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread
Community comments

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Discuss

Educational Content

General Feedback
Bugs
Advertising
Editorial
InfoQ.com and all content copyright © 2006-2013 C4Media Inc. InfoQ.com hosted at Contegix, the best ISP we've ever worked with.
Privacy policy
BT