何时创建新任务

时间:2013-09-10 14:18:10

标签: c# .net asynchronous task-parallel-library async-await

我正在学习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;
}

两者有什么区别?哪一个更好?

1 个答案:

答案 0 :(得分: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;
}

另请注意,该示例使用了日期WebClient,该代码应在新代码中替换为HttpClient

总的来说,它看起来只是一个不好的例子IMO。