我在查看异步代码的示例时注意到它的实现存在一些问题。在查看代码时,我想知道使用并行方式循环遍历列表是否比普通方式更有效率。
据我所知,性能方面几乎没有什么区别,两种方式都会占用所有处理器,并且花费完成时间也大致相同。
下面是第一种实现方式:
据我所知,性能方面几乎没有什么区别,两种方式都会占用所有处理器,并且花费完成时间也大致相同。
下面是第一种实现方式:
var tasks= Client.GetClients().Select(async p => await p.Initialize());
这是第二个
var tasks = Client.GetClients().AsParallel().Select(async p => await p.Initialize());
我猜想两者之间没有区别,我的猜想正确吗?
完整的程序可以在下面找到。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
RunCode1();
Console.WriteLine("Here");
Console.ReadLine();
RunCode2();
Console.WriteLine("Here");
Console.ReadLine();
}
private async static void RunCode1()
{
Stopwatch myStopWatch = new Stopwatch();
myStopWatch.Start();
var tasks= Client.GetClients().Select(async p => await p.Initialize());
Task.WaitAll(tasks.ToArray());
Console.WriteLine("Time ellapsed(ms): " + myStopWatch.ElapsedMilliseconds);
myStopWatch.Stop();
}
private async static void RunCode2()
{
Stopwatch myStopWatch = new Stopwatch();
myStopWatch.Start();
var tasks = Client.GetClients().AsParallel().Select(async p => await p.Initialize());
Task.WaitAll(tasks.ToArray());
Console.WriteLine("Time ellapsed(ms): " + myStopWatch.ElapsedMilliseconds);
myStopWatch.Stop();
}
}
class Client
{
public static IEnumerable<Client> GetClients()
{
for (int i = 0; i < 100; i++)
{
yield return new Client() { Id = Guid.NewGuid() };
}
}
public Guid Id { get; set; }
//This method has to be called before you use a client
//For the sample, I don't put it on the constructor
public async Task Initialize()
{
await Task.Factory.StartNew(() =>
{
Stopwatch timer = new Stopwatch();
timer.Start();
while(timer.ElapsedMilliseconds<1000)
{}
timer.Stop();
});
Console.WriteLine("Completed: " + Id);
}
}
}
Thread.Sleep(time);
代替所有那些秒表代码) - matthewr