7

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?

4

1 回答 1

6

好吧,这个例子专门展示了如何使用Task.FromResult,你的第二个代码没有使用。也就是说,我不同意Task.Run示例中的用法。

我自己会这样写:

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;
}

另请注意,该示例使用了 dated WebClient,应HttpClient在新代码中将其替换为。

总的来说,它看起来只是一个糟糕的 IMO 示例。

于 2013-09-10T14:42:25.387 回答