刚才我已经发布了这个问题涉及到在客户端或服务应用异步等待.在继续讨论这个问题之前,请先阅读问题,因为它与问题紧密相关.
根据答案我已经测试了C#4.0(TPL)和C#5.0(Async - Await)的代码.我使用服务提供的方法的异步和同步版本来调用服务,并比较每种情况下使用的线程数.以下是我用于测试所用资源的代码:
主要方法
List<Task<string>> tasksList = new List<Task<string>>();
List<int> asyncThreads = new List<int>();
List<int> tplThreads = new List<int>();
Stopwatch watch = new Stopwatch();
watch.Start();
// Call the Async version of the method
for (int i = 0; i < 500; i++)
{
tasksList.Add(GetNameFromServiceAsync("Input" + i.ToString(), asyncThreads));
}
Task.WaitAll(tasksList.ToArray());
watch.Stop();
foreach (var item in asyncThreads.Distinct())
{
Console.WriteLine(item);
}
Console.WriteLine("(C# 5.0)Asynchrony Total Threads = " + asyncThreads.Distinct().Count());
Console.WriteLine(watch.ElapsedMilliseconds.ToString());
watch.Restart();
tasksList.Clear();
// Call the normal method
for (int i …Run Code Online (Sandbox Code Playgroud)