Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

run a method multiple times simultaneously in c#

I have a method that returns XML elements, but that method takes some time to finish and return a value.

What I have now is

foreach (var t in s)
{
    r.add(method(test));
}

but this only runs the next statement after previous one finishes. How can I make it run simultaneously?

like image 580
ikel Avatar asked Dec 03 '22 00:12

ikel


2 Answers

You should be able to use tasks for this:

//first start a task for each element in s, and add the tasks to the tasks collection
var tasks = new List<Task>();
foreach( var t in s)
{
    tasks.Add(Task.Factory.StartNew(method(t)));
}

//then wait for all tasks to complete asyncronously
Task.WaitAll(tasks);

//then add the result of all the tasks to r in a treadsafe fashion
foreach( var task in tasks)
{
  r.Add(task.Result);
}

EDIT There are some problems with the code above. See the code below for a working version. Here I have also rewritten the loops to use LINQ for readability issues (and in the case of the first loop, to avoid the closure on t inside the lambda expression causing problems).

var tasks = s.Select(t => Task<int>.Factory.StartNew(() => method(t))).ToArray();

//then wait for all tasks to complete asyncronously
Task.WaitAll(tasks);

//then add the result of all the tasks to r in a treadsafe fashion
r = tasks.Select(task => task.Result).ToList();
like image 143
Øyvind Bråthen Avatar answered Dec 23 '22 00:12

Øyvind Bråthen


You can use Parallel.ForEach which will utilize multiple threads to do the execution in parallel. You have to make sure that all code called is thread safe and can be executed in parallel.

Parallel.ForEach(s, t => r.add(method(t));
like image 39
Anders Abel Avatar answered Dec 23 '22 00:12

Anders Abel