简体   繁体   中英

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.

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). Also, Parallel is taking more time than tasks. 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.

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

You need to form a closure over 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. If the problem isn't CPU bound (ie calling WebServices) Parallel is not the right abstraction.

So in your case it seems Task is the right choice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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