Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parallel.foreach multiple arguments being passed to method

I am calling a method in parallel which works fine, but I want to have it pass a object to it.

This works:

static void main()
{
Parallel.ForEach(_queued, new ParallelOptions { MaxDegreeOfParallelism = config.downloadthreads }, DownloadFile);
}
public static void DownloadFile(string url)
{....
}

But what I want to do is to pass config which is a class I have defined earlier to the downloadfile method. I have been keeping my settings and other stuff in the class and then updating them so that I don't need to pass variables all over the place. But when I try that, I get a bunch of errors

cannot convert from void to system.action , _queued is a concurrentqueue

Parallel.ForEach(_queued, new ParallelOptions 
{ MaxDegreeOfParallelism = config.downloadthreads }, DownloadFile(_queued, config));

public static void DownloadFile(string url, blogconfig tumblogconfig)
like image 966
user3395025 Avatar asked Mar 08 '14 03:03

user3395025


People also ask

Is parallel ForEach blocking?

No, it doesn't block and returns control immediately. The items to run in parallel are done on background threads.

Is parallel ForEach multiple threads?

ForEach loop works like a Parallel. For loop. The loop partitions the source collection and schedules the work on multiple threads based on the system environment. The more processors on the system, the faster the parallel method runs.

Does ForEach execute in parallel?

ForEach will always execute in parallel.

Is parallel ForEach faster than ForEach?

The execution of Parallel. Foreach is faster than normal ForEach.


1 Answers

You need to create a lambda and call your function from inside it.

Parallel.ForEach(_queued, 
                 new ParallelOptions { MaxDegreeOfParallelism = config.downloadthreads }, 
                 (q) => DownloadFile(q, config));
like image 185
Scott Chamberlain Avatar answered Oct 08 '22 21:10

Scott Chamberlain