I am learning about Task Parallelism in C#.NET 4.5, and I am a little confused about an example. Here is the code I don't understand:
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;
});
}
Specifically, I don't understand why they are wrapping DownloadStringTaskAsync()
in another task. Isn't DownloadStringTaskAsync()
already running on its own thread?
Here is the way I would have coded it:
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;
}
What is the difference between the two? Which one is better?