c# – 何时创建新任务

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

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

解决方法

好吧,这个例子具体说明了如何使用你的第二个代码不使用的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.

相关文章

项目中经常遇到CSV文件的读写需求,其中的难点主要是CSV文件...
简介 本文的初衷是希望帮助那些有其它平台视觉算法开发经验的...
这篇文章主要简单记录一下C#项目的dll文件管理方法,以便后期...
在C#中的使用JSON序列化及反序列化时,推荐使用Json.NET——...
事件总线是对发布-订阅模式的一种实现,是一种集中式事件处理...
通用翻译API的HTTPS 地址为https://fanyi-api.baidu.com/api...