I've been trying to learn how to use the TPL for quite some time now. Basically I'm trying to fire off a group of Tasks, wait for them to complete and then fire off another group of tasks, waiting for them to complete before firing off the tasks that update form elements on the UI Thread.
Here's what I got. I think I'm probably overcomplicating it however it does seem to work as I want it too. Please could I have some advice on how I could simplify this based on what I want to achieve?
private async Task PrepareData()
{
Task[] FirstTasks = new Task[] { TaskOne(), TaskTwo() }; // Do First group of Tasks
await Task.WhenAll(FirstTasks); // Wait for First group of Tasks
Task[] SecondTasks = new Task[] { TaskThree(), TaskFour() }; // Do Second group of Tasks
await Task.WhenAll(SecondTasks).ContinueWith(c => // Wait for Second group of Tasks
{
GuiTaskOne();
GuiTaskTwo();
}, TaskScheduler.FromCurrentSynchronizationContext()); // Then update the form on the UI Thread
}
private async Task TaskOne()
{
someVariable = await Task.Run(() => DoSomething());
}
private async Task TaskTwo()
{
someVariable = await Task.Run(() => DoSomething());
}
private async Task TaskThree()
{
someVariable = await Task.Run(() => DoSomething());
}
private async Task TaskFour()
{
someVariable = await Task.Run(() => DoSomething());
}
private async Task GuiTaskOne()
{
someControl.Text = await Task.Run(() => DoSomething());
}
private async Task GuiTaskTwo()
{
someControl.Text = await Task.Run(() => DoSomething());
}
DoSomething()
is just a method that runs something likeThread.Sleep(1000);
? – Mat's Mug♦ Feb 24 '14 at 13:47TaskThree
andGuiTaskOne
(and the others).. right now it looks like all tasks call the sameDoSomething
method. I know in reality it's probably not the case, but since reviewers can comment on any aspect of your code, it'd be nice if your code wasn't too narrowed down on theasync/await
mechanics. – Mat's Mug♦ Feb 24 '14 at 15:14