Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# .NET Tasks: How to get notification when multiple tasks have completed

In my WPF application, I need to run 2 long running tasks in parallel, both which return data that needs to be shown in the UI.

I have a a property in my view model called IsBusy, which should be true until both tasks have completed.

How to I get a notification when the 2 long running tasks have completed?

I don't want to use Task.WaitAll, because it will block my UI thread. I don't want to chain the tasks using ContinueWith, because I want those long running tasks to run in parallel.

like image 474
Mas Avatar asked Aug 04 '11 14:08

Mas


3 Answers

Use TaskScheduler.FromCurrentSynchronizationContext() and pass it to TaskFactory.ContinueWhenAll(...) to do UI update after both tasks completed.

like image 58
QrystaL Avatar answered Oct 22 '22 07:10

QrystaL


One way would be to create a third thread that spawns those tasks, and uses Task.WaitAll to delay thread exit until the two tasks complete. At the end of that thread you can fire an event or execute a callback function.

You could make it even easier by using BackgroundWorker, which has a built-in event called RunWorkerCompleted. This would put you on the thread pool so you don't have to be as concerned with managing that thread.

like image 27
drharris Avatar answered Oct 22 '22 09:10

drharris


Try Task.Factory.ContinueWhenAll. It takes an array of Tasks and asynchronously fires off an operation when they are all complete.

like image 4
tom.dietrich Avatar answered Oct 22 '22 09:10

tom.dietrich