Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RunAsync - How do I await the completion of work on the UI thread?

When awaiting Dispatcher.RunAsync the continuation occurs when the work is scheduled, not when the work has completed. How can I await the work completing?

Edit

My original question assumed the premature continuation was caused by the design of the API, so here's the real question.

When awaiting Dispatcher.RunAsync using an asynchronous delegate, using await within the delegate's code, the continuation occurs when the await is encountered, not when the work has completed. How can I await the work completing?

Edit 2

One reason you may need to dispatch work that's already on the UI thread is to workaround subtle timing and layout issues. It's quite common for values of sizes and positions of elements in the visual tree to be in flux and scheduling work for a later iteration of the UI can help.

like image 681
Luke Puplett Avatar asked Oct 02 '13 09:10

Luke Puplett


Video Answer


1 Answers

Your question is assuming that you want to schedule (and wait for) work on a UI thread from a background thread.

You'll usually find your code is much cleaner and easier to understand (and it will definitely be more portable) if you have the UI be the "master" and the background threads be the "slaves".

So, instead of having a background thread await some operation for the UI thread to do (using the awkward and unportable Dispatcher.RunAsync), you'll have the UI thread await some operation for the background thread to do (using the portable, made-for-async Task.Run).

like image 187
Stephen Cleary Avatar answered Oct 20 '22 13:10

Stephen Cleary