Я узнаю о параллелизме задач в C# .NET 4.5, и я немного смущен о example. Вот код, который я не понимаю:Когда создавать новую задачу
public static Task<string> DownloadStringAsync(string address)
{
// First try to retrieve the content from cache.
string content;
if (cachedDownloads.TryGetValue(address, out content))
{
return Task.FromResult<string>(content);
}
// If the result was not in the cache, download the
// string and add it to the cache.
return Task.Run(async() => // why create a new task here?
{
content = await new WebClient().DownloadStringTaskAsync(address);
cachedDownloads.TryAdd(address, content);
return content;
});
}
В частности, я не понимаю, почему они оборачивают DownloadStringTaskAsync()
в другой задаче. Разве не DownloadStringTaskAsync()
уже работает в своей собственной теме?
Вот как я бы закодировал:
public static async Task<string> DownloadStringAsync(string address)
{
// First try to retrieve the content from cache.
string content;
if (cachedDownloads.TryGetValue(address, out content))
{
return content;
}
// If the result was not in the cache, download the
// string and add it to the cache.
content = await new WebClient().DownloadStringTaskAsync(address);
cachedDownloads.TryAdd(address, content);
return content;
}
В чем разница между ними? Какая из них лучше?
Бывший работает над несколькими потоками последнего нет (поскольку, вероятно, WebClient.DownloadStringTaskAsync не использует Task.Run, обратите внимание, что второе должно быть предпочтительным, так как пользователь не ожидает появления нового потока при использовании метода async –