When to create a new task

I am studying the Parallelism problem in C # .NET 4.5 and I am a bit confused in the example . Here is the code that I do not 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; }); } 

In particular, I do not understand why they transfer DownloadStringTaskAsync() to another task. Is DownloadStringTaskAsync() already running in its thread?

Here's how I would encode 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?

+7
c # asynchronous task-parallel-library async-await
source share
1 answer

Well, the example shows how to use Task.FromResult , which your second code does not use. However, I do not agree with the use of Task.Run in this example.

I would write it like this:

 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(content); } // If the result was not in the cache, download the // string and add it to the cache. return DownloadAndCacheStringAsync(address); } private static async Task<string> DownloadAndCacheStringAsync(string address) { var content = await new WebClient().DownloadStringTaskAsync(address); cachedDownloads.TryAdd(address, content); return content; } 

Also note that the example uses a dated WebClient , which should be replaced with HttpClient in the new code.

All in all, this looks like a bad IMO example.

+5
source share

All Articles