Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a foreach loop to a Parallel.ForEach loop

Okay, so here is the basic background. This program connects to outlook/exchange and parses through all the mail messages to see which are encrypted. One of the things I would like to do is to use multi-threading to decrease the time it takes to scan through the messages.

Currently the code looks like this:

foreach (Object item in folder.Items) {
//Checks for encryption and gets needed info and updates count
}

And I would like to utilize the Parallel.ForEach function instead. I was wondering how I could set it up. I tried setting up the expression to how it is now, but I get an error stating that the Object type is being used as a variable. Any help with this would be greatly appreciated.

Okay, The layout I have been given seems to be correct. The code looks like this right now:

Parallel.ForEach(folder.Items, item =>
{
//does stuff
});

I am now getting the following error:

Error 15 The type arguments for method System.Threading.Tasks.Parallel.ForEach(System.Collections.Concurrent.OrderablePartitioner, System.Action)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Any ideas? Thanks for your help guys, it is appreciated.

Okay, I found this site: http://blogs.msdn.com/b/pfxteam/archive/2010/03/02/9971804.aspx and it gave me the answer I needed to the error. I just needed to change the collection to a generic one by making a casting function.

static IEnumerable<object> Cast(IEnumerable source)
{
    foreach (object o in source)
        yield return o;
}

And then tweak the original to

Parallel.ForEach(Cast(folder.Items), item =>
{
//does stuff
});

Now it runs without errors. Hurray.

like image 906
Micro125 Avatar asked Nov 21 '11 19:11

Micro125


1 Answers

Something like this:

Parallel.For(0, folder.Items.Count - 1, delegate(int i) { 
  object item = folder.Items[i];
});

Or with ForEach:

Parallel.ForEach(folder.Items, item => {whatever you want to do with item})

Note: folder.Items has to be implementing IEnumerable

like image 193
Andrey Avatar answered Sep 26 '22 18:09

Andrey