我有一份样本代码,可以比较并行方法和任务方法的处理时间。实验的目的是了解它们的工作方式。
那么我的问题是:
- 为什么并行方法比任务方法更快?
- 我的结果是否意味着我应该使用并行而不是任务?
- 在哪些情况下应该使用任务和并行?
- 与使用并行相比,使用任务的好处是什么?
任务只是 ThreadPool.QueueUserWorkItem 方法的包装吗?
public Task SomeLongOperation()
{
return Task.Delay(3000);
}
static void Main(string[] args)
{
Program p = new Program();
List<Task> tasks = new List<Task>();
tasks.Add(Task.Factory.StartNew(() => p.SomeLongOperation()));
tasks.Add(Task.Factory.StartNew(() => p.SomeLongOperation()));
var arr = tasks.ToArray();
Stopwatch sw = Stopwatch.StartNew();
Task.WaitAll(arr);
Console.WriteLine("Task wait all results: " + sw.Elapsed);
sw.Stop();
sw = Stopwatch.StartNew();
Parallel.Invoke(() => p.SomeLongOperation(), () => p.SomeLongOperation());
Console.WriteLine("Parallel invoke results: " + sw.Elapsed);
sw.Stop();
Console.ReadKey();
}
以下是我的处理结果:
编辑:
将代码更改为以下内容:
Program p = new Program();
Task[] tasks = new Task[2];
Stopwatch sw = Stopwatch.StartNew();
tasks[0] = Task.Factory.StartNew(() => p.SomeLongOperation());
tasks[1] = Task.Factory.StartNew(() => p.SomeLongOperation());
Task.WaitAll(tasks);
Console.WriteLine("Task wait all results: " + sw.Elapsed);
sw.Stop();
sw = Stopwatch.StartNew();
Parallel.Invoke(() => p.SomeLongOperation(), () => p.SomeLongOperation());
Console.WriteLine("Parallel invoke results: " + sw.Elapsed);
sw.Stop();
我的新结果:
编辑2: 当我把代码替换为Parallel.Invoke排在第一位,Task.WaitAll排在第二位时,情况发生了彻底改变。现在Parallel的速度更慢了。这让我想到我的估计可能是不正确的。我把代码改成了这样:
Program p = new Program();
Task[] tasks = new Task[2];
Stopwatch sw = null;
for (int i = 0; i < 10; i++)
{
sw = Stopwatch.StartNew();
Parallel.Invoke(() => p.SomeLongOperation(), () => p.SomeLongOperation());
string res = sw.Elapsed.ToString();
Console.WriteLine("Parallel invoke results: " + res);
sw.Stop();
}
for (int i = 0; i < 10; i++)
{
sw = Stopwatch.StartNew();
tasks[0] = Task.Factory.StartNew(() => p.SomeLongOperation());
tasks[1] = Task.Factory.StartNew(() => p.SomeLongOperation());
Task.WaitAll(tasks);
string res2 = sw.Elapsed.ToString();
Console.WriteLine("Task wait all results: " + res2);
sw.Stop();
}
以下是我的新结果:
现在我可以建议这个实验更加清晰。结果几乎相同。 有时Parallel更快,有时Task更快。 现在我的问题是:
1. 在哪些情况下应该使用Task和Parallel?
2. 相比Parallel,使用Task的好处是什么?
3. Task只是ThreadPool.QueueUserWorkItem方法的包装吗?
欢迎提供任何有助于澄清这些问题的信息。