var tasks = new List<Task>();
foreach (var guid in guids)
{
var task = new Task( ...);
tasks.Add(task);
}
foreach (var task in tasks)
{
task.Start();
Task.WaitAll(task);
}
This is run of the UI thread. I need to execute all tasks in tasks variable one after the other. The problem is if I call Task.WaitAll(task), the UI freeze. How can I do the following logic without having the UI freeze?
This is not Task Chaining.
You need to do Task chaining using
ContinueWith
. Last task would need to update the UI.Note the last line has
TaskScheduler.FromCurrentSynchronizationContext()
this will ensure task will run in the synchronization context (UI Thread).The best way is to use the Task Parallel Library (TPL) and Continuations. A continuation not only allows you to create a flow of tasks but also handles your exceptions. This is a great introduction to the TPL. But to give you some idea...
You can start a TPL task using
Now to start a second task when an antecedent task finishes (in error or successfully) you can use the
ContinueWith
methodSo as soon as
task1
completes, fails or is cancelledtask2
'fires-up' and starts running. Note that iftask1
had completed before reaching the second line of codetask2
would be scheduled to execute immediately. TheantTask
argument passed to the second lambda is a reference to the antecedent task. See this link for more detailed examples...You can also pass continuations results from the antecedent task
Note. Be sure to read up on exception handling in the first link provided as this can lead a newcomer to TPL astray.
One last thing to look at in particular for what you want is child tasks. Child tasks are those which are created as
AttachedToParent
. In this case the continuation will not run until all child tasks have completedI hope this helps.
You need to use continutations: