简体   繁体   English

c#中的并行与任务

[英]Parallel vs Tasks in c#

I have a method where it need to make multiple service calls and consolidate the result. 我有一个方法,它需要进行多个服务调用并合并结果。 Was trying to use Task for this and the results were not right, so I did the below two tests. 试图使用Task这个并且结果不对,所以我做了以下两个测试。

Using Tasks 使用任务

List<Task<string>> tasks = new List<Task<string>>();
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < 20; i++)
{
    tasks.Add(Task.Factory.StartNew(() =>
        {
            long started = stopwatch.ElapsedMilliseconds;
            Random wait = new Random();
            int waited = wait.Next(500, 3000);
            Thread.Sleep(waited);
            return string.Format("Index #{0} started at {1}ms and waited {2}ms", i, started, waited);
        }));
}

Task.WaitAll(tasks.ToArray());
foreach (Task<string> task in tasks)
{
    Console.WriteLine(string.Format("[Task {0,2}] {1}", task.Id, task.Result));
}

Using Parallel 使用并行

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
int[] inputs = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };
Parallel.ForEach(inputs, i =>
{
    long started = stopwatch.ElapsedMilliseconds;
    Random wait = new Random();
    int waited = wait.Next(500, 3000);
    Thread.Sleep(waited);
    string result = string.Format("Task {0,2} started at {1} ms and waited {2} ms", i, started, waited);
    Console.WriteLine(result);
});

stopwatch.Stop();
Console.WriteLine("Total time taken: " + stopwatch.ElapsedMilliseconds.ToString());

As you can see below, the task index gets printed as 20 all the time (though 0 to 19 was passed). 如下所示,任务索引始终打印为20(虽然传递了0到19)。 Also, Parallel is taking more time than tasks. 此外,Parallel比任务花费更多时间。 Below are the results, and obviously am doing something wrong in Tasks and is unable to figure out what :( 以下是结果,显然我在任务中做错了,无法弄清楚:(

Task Output 任务输出

[Task  1] Index #20 started at 0ms and waited 875ms
[Task  2] Index #20 started at 0ms and waited 875ms
[Task  3] Index #20 started at 0ms and waited 875ms
[Task  4] Index #20 started at 0ms and waited 875ms
[Task  5] Index #20 started at 0ms and waited 875ms
[Task  6] Index #20 started at 0ms and waited 875ms
[Task  7] Index #20 started at 855ms and waited 1477ms
[Task  8] Index #20 started at 886ms and waited 1965ms
[Task  9] Index #20 started at 886ms and waited 1965ms

Parallel Output 并行输出

Task  6 started at 1046 ms and waited 636 ms
Task 11 started at 1561 ms and waited 758 ms
Task  0 started at 16 ms and waited 2891 ms
Task  5 started at 16 ms and waited 2891 ms
Task 15 started at 17 ms and waited 2891 ms
Task  1 started at 17 ms and waited 2891 ms
Task 10 started at 17 ms and waited 2891 ms

With actual method too I've the same experience where the last item is being returned multiple times rather than individual results. 使用实际方法我也有相同的经验,其中最后一项被多次返回而不是单独的结果。

Would be of great help if you can guide me in the right direction. 如果你能引导我朝着正确的方向前进,那将会有很大的帮助。

Note: The outputs are partial. 注意:输出是部分的。 Actual output has 20 items each. 实际产量各有20项。

当使用Tasks方法时,你在'i'上有一个闭包,这就是为什么所有的任务ID都是20(即在任务实际执行时,所有20个都已经被安排,因此i == 20,当方法执行时)。

You need to form a closure over i . 你需要在i上形成一个闭包。 Here's the easiest way: 这是最简单的方法:

for (int x = 0; x < 20; x++)
{
    var i = x;
    tasks.Add(...) // keep using `i` inside here & never `x`
}

That should fix it. 那应该解决它。

Parallel is primarily intended to allow you to scale your algorithms to use the available CPU resources on your machine. Parallel主要用于扩展算法以使用计算机上的可用CPU资源。 If the problem isn't CPU bound (ie calling WebServices) Parallel is not the right abstraction. 如果问题不是CPU绑定(即调用WebServices)并行不是正确的抽象。

So in your case it seems Task is the right choice. 所以在你的情况下,似乎任务是正确的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM