How to Wait Until Task.ContinueWith Internal Task Finishes

Take a look at this code:

private async Task InnerTask(bool outerTaskResult) { Console.WriteLine("2"); await Task.Factory.StartNew(() => Thread.Sleep(10000)); Console.WriteLine("3"); } private async void Button2_Click(object sender, RoutedEventArgs e) { var task = Task.FromResult(false); Task<Task> aggregatedTask = task.ContinueWith(task1 => InnerTask(task1.Result)); Console.WriteLine("1"); await aggregatedTask; Console.WriteLine("4"); } 

Required Result:

 1 2 3 4 

But I get:

 1 2 4 3 

Perhaps this is due to the fact that InnerTask is running in another thread.

I use ContinueWith because tasks in the source code are dynamically created and queued this way.

Using the .Wait () method (see below) works, but I think this is a bad idea, as the method blocks.

 task.ContinueWith(task1 => InnerTask(task1.Result).Wait()) 

What is the right approach here?

+7
c # task-parallel-library async-await task
source share
1 answer

You can use TaskExtensions.Unwrap() (which is the extension method on Task<Task> ) to deploy the outter task and get the internal one:

 private async void Button2_Click(object sender, RoutedEventArgs e) { var task = Task.FromResult(false); Task aggregatedTask = task.ContinueWith(task1 => InnerTask(task1.Result)).Unwrap(); Console.WriteLine("1"); await aggregatedTask; Console.WriteLine("4"); } 

Note that to simplify all this, instead of continuing with the ContinueWith style, you can await to complete your tasks:

 private async void Button2_Click(object sender, RoutedEventArgs e) { var task = Task.FromResult(false); Console.WriteLine("1"); var result = await task; await InnerTask(result); Console.WriteLine("4"); } 
+8
source share

All Articles