Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for Parallel.For

I know that there is no need to wait for a Parallel.For but since UI Windows messages (WinForms message pump) are being processed during the Parallel.For I would like to wait for Parallel.For to finish.

Is it a good idea to encapsulate a Parallel.For inside a Task, then wait for it? Is there any better approach?

Thanks.

CancellationTokenSource token = new CancellationTokenSource();

const int len = 100;

double[] array = new double[len];

Task t = Task.Factory.StartNew(delegate {
   Parallel.For(0, len, delegate(int i, ParallelLoopState loopState) {

   array[i] += 1;

   });

try
{
   t.Wait(token.Token);
}
catch (OperationCanceledException e)
{
   rc = false;
}
like image 363
abenci Avatar asked Dec 15 '22 01:12

abenci


1 Answers

Instead of Parallel.For why not use just Task and call Task.WaitAll()?

var t1 = Task.Run(() => {});
var t2 = Task.Run(() => {});

Task.WaitAll(t1, t2);
like image 59
Mayank Avatar answered Jan 01 '23 21:01

Mayank