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.
Stephen cleary
source share