System.Threading.Tasks & # 8594; Continuations

Let's say you have a service:

interface ISuessService { Task<Thing> Thing1(); Task<Thing> Thing2(); } 

And I have a ContinueOnUIThread extension method where I can do cool things like:

 myService.Thing1().ContinueOnUIThread(_ => label.Text = "Done!"); 

and easy to interact with the user interface thread.

What is the best way to implement the new ContinueWith extension method that does this:

 myService.Thing1() .ContinueWith(myService.Thing2()) .ContinueOnUIThread(_ => label.Text = "Done!"); 

Thing2 basically starts after Thing2 completes, followed by a UI thread call.

The closest I came is something like this, but I really don't like calling Wait :

 myService.Thing1() .ContinueWith(_ => { var thing2 = myService.Thing2().Wait(); return thing2.Result; }) .ContinueOnUIThread(_ => label.Text = "Done!"); 

Is there a clean way to do this?

PS - I do not have .Net 4.5, so there is no waiting / asynchrony - this code should work on MonoTouch / Mono for Android, so stick with 4.0

PS - pay attention to my use of _ , it's just a shortcut for "I really don't use this parameter"

+4
source share
1 answer

I think you can look for the Unwrap method from System.Threading.Tasks.TaskExtensions

 myService.Thing1() .ContinueWith(_ => myService.Thing2()).Unwrap() .ContinueOnUIThread(_ => label.Text = "Done!"); 
+3
source

Source: https://habr.com/ru/post/1440154/


All Articles