Download Master Thesis
Transcript
The asynchronous code written using these two new keywords looks almost the
same as the synchronous code, but it is executed asynchronously. The keyword
async in the method signature means that it can use the await keyword. If there
is no await keyword in the body of such method, it will be executed
synchronously as any other method. The await keyword is applied to a task
inside an asynchronous method meaning that when the execution of the method
reaches this point, it is suspended until the awaited task is completed. This makes
asynchronous programming easier and the code cleaner because there is no need
to define callbacks when an asynchronous method completes its execution.
Tasks combined with async and await are particularly useful when it comes to
loading and parsing many files in the project. These tasks can run in parallel and
we need to know when they all finish. The solution to this problem is, according
to the Async in C# 5.0 [13], to use Task.WhenAll, which is a utility that can take
many tasks and produce one aggregated Task that will complete once all the
inputs complete. The Figure 5 describes the usage of this utility:
public async void LoadFiles(string[] paths)
{
List<Task> tasks = new List<Task>();
// create new tasks
for(int i = 0; i < paths.Length; i++)
tasks.Add(LoadFile(paths[i]));
// start all tasks
tasks.ForEach(t => t.Start());
// wait until all tasks finish
await Task.WhenAll(tasks);
// notify the user that all files were loaded
MessageBox.Show("Files loaded.");
}
public Task LoadFile(string path)
{
return new Task(() =>
{
// loading, parsing, etc.
});
}
Figure 5 Task.WhenAll sample code
15