0

尝试在 .NET 4.0 Async CTP 中运行 C# 代码示例“如何:创建预计算任务”(MSDN),并进行了更改:

  • Task.FromResult--->TaskEx.FromResult
  • Task.FromResult--->TaskEx.FromResult
  • Task.Run(async () => ---> TaskEx.RunEx(async () =>
    (也试过TaskEx.Run(async () =>

对接得到编译错误:

由于 ' System.Func<System.Threading.Tasks.Task>' 是 async 并返回 Task,因此 return 关键字后面不能跟对象表达式

如何更改代码以运行此示例?

using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

// Demonstrates how to use Task<TResult>.FromResult to create a task  
// that holds a pre-computed result. 
class CachedDownloads
{
  // Holds the results of download operations. 
  static ConcurrentDictionary<string, string> cachedDownloads =
     new ConcurrentDictionary<string, string>();

  // Asynchronously downloads the requested resource as a string. 
  public static Task<string> DownloadStringAsync(string address)
  {
    // First try to retrieve the content from cache. 
    string content;
    if (cachedDownloads.TryGetValue(address, out content))
    {

      return TaskEx //****** Task.FromResult ---> TaskEx.FromResult   
             .FromResult<string>(content);
    }

    // If the result was not in the cache, download the  
    // string and add it to the cache. 
    return TaskEx.RunEx //****** Task.Run  --> TaskEx.RunEx (TaskEx.Run)
      (async () =>    
    {
      content = await new WebClient().DownloadStringTaskAsync(address);
      cachedDownloads.TryAdd(address, content);
      return content;//*****Error
    });
  }

  static void Main(string[] args)
  {
    // The URLs to download. 
    string[] urls = new string[]
      {
         "http://msdn.microsoft.com",
         "http://www.contoso.com",
         "http://www.microsoft.com"
      };

    // Used to time download operations.
    Stopwatch stopwatch = new Stopwatch();

    // Compute the time required to download the URLs.
    stopwatch.Start();
    var downloads = from url in urls
                    select DownloadStringAsync(url);
    TaskEx.WhenAll(downloads)//*** Task.WhenAll -->  TaskEx.WhenAll
          .ContinueWith(results =>
    {
      stopwatch.Stop();

      // Print the number of characters download and the elapsed time.
      Console.WriteLine
            ("Retrieved {0} characters. Elapsed time was {1} ms."
              , results.Result.Sum(result => result.Length)
              , stopwatch.ElapsedMilliseconds);
    })
    .Wait();

    // Perform the same operation a second time. The time required 
    // should be shorter because the results are held in the cache.
    stopwatch.Restart();
    downloads = from url in urls
                select DownloadStringAsync(url);

    TaskEx.WhenAll(downloads)//*** Task.WhenAll -->  TaskEx.WhenAll
          .ContinueWith(results =>
    {
      stopwatch.Stop();

      // Print the number of characters download and the elapsed time.
      Console.WriteLine("Retrieved {0} characters. Elapsed time was {1} ms.",
         results.Result.Sum(result => result.Length),
         stopwatch.ElapsedMilliseconds);
    })
    .Wait();
  }
}

更新:

没有我对 Async CTP 的更新的此代码示例是否在 .NET 4.5 中运行?

4

1 回答 1

3

C# 编译器在 VS2012 中得到了增强,以便在存在asynclambda(即Func<Task>和家族)的情况下更智能地处理泛型重载解析。由于您使用的是 VS2010,因此您必须在这里和那里提供帮助。

The clue is in the type of your async lambda as displayed in your error message: System.Func<System.Threading.Tasks.Task>.

What it should be is System.Func<System.Threading.Tasks.Task<System.String>>.

So I would try this:

return TaskEx.RunEx<string> //****** Task.Run  --> TaskEx.RunEx (TaskEx.Run)
  (async () =>    
{
  content = await new WebClient().DownloadStringTaskAsync(address);
  cachedDownloads.TryAdd(address, content);
  return content;//*****Error
});
于 2013-05-07T18:19:01.997 回答