試圖在.NET運行C#代碼示例"How to: Create Pre-Computed Tasks" (MSDN) 4.0異步CTP,在作出改變:如何運行MSDN代碼示例「如何創建預計算任務」?
Task.FromResult
--->TaskEx.FromResult
Task.FromResult
--->TaskEx.FromResult
Task.Run(async() =>
--->TaskEx.RunEx(async() =>
(也試過TaskEx.Run(async() =>
)
對接總體性他編譯錯誤:
Since '
System.Func<System.Threading.Tasks.Task>
' is async and returns Task, a return keyword must not be followed by an object expression
如何更改代碼以運行此示例?
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();
}
}
更新:
難道沒有我的異步CTP更新此代碼示例運行在.NET 4.5?
:
所以我會嘗試嗎?這可能很容易成爲CTP中的一個已修復的錯誤。 – dlev 2013-05-07 18:01:10
由於RTM不能在Windows XP和.NET 4.0中安裝,因爲.NET 4.5與不安裝4.5的計算機上的.NET 4.0不同 – 2013-05-07 18:13:08