'Difference between await and manual Task handling
I would like someone to clarify the difference between awaiting many Tasks and manually waiting for their completion in a collection.
I have an XML reader class that has to process several hundred files and while optimizing it I found an interesting difference. I created two functions, both of which calls my
private async Task ParseModelsFromFile(ConcurrentDictionary<TSettings, TResults> datas, string filePath) function. This basically loads all my models from the XML file on the given filePath. The only difference is in the calling and awaiting of this ParseModelsFromFile() function.
The first function: ProcessFiles() uses the await keyword, the second: ProcessFilesWithTasks creates a Task object for every single filePath, puts it in a collection of Tasks and waits for all of them to complete.
The second version with the Task collection is much faster. It takes about half the time. I was thinking that these two functions will do the same thing and the only difference is going to be the use of the async keyword.
I did test this with several amounts of files and the function using await always comes out to be about 2x slower.
private async Task ProcessFiles(ConcurrentDictionary<TSettings, TResults> datas, BlockingCollection<string> filePaths)
{
if (filePaths.Count == 0)
return;
foreach (var filePath in filePaths.GetConsumingEnumerable())
{
await ParseModelsFromFile(datas, filePath);
}
}
private Task ProcessFilesWithTasks(ConcurrentDictionary<TSettings, TResults> datas, BlockingCollection<string> filePaths)
{
if (filePaths.Count == 0)
return Task.CompletedTask;
List<Task> runningTasks = new List<Task>();
foreach (var filePath in filePaths.GetConsumingEnumerable())
{
runningTasks.Add(ParseModelsFromFile(datas, filePath));
}
Task allTasks = Task.WhenAll(runningTasks.ToArray());
allTasks.Wait();
return Task.CompletedTask;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
