[英]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.
该程序连接到outlook / exchange并解析所有邮件消息以查看哪些是加密的。 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. 我想改用Parallel.ForEach函数。 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.
我尝试将表达式设置为现在的样式,但是我得到一个错误,指出Object类型被用作变量。 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.
错误15无法从用法推断出方法System.Threading.Tasks.Parallel.ForEach(System.Collections.Concurrent.OrderablePartitioner,System.Action)的类型参数。 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. 好的,我找到了这个网站: http : //blogs.msdn.com/b/pfxteam/archive/2010/03/02/9971804.aspx ,它给了我错误所需的答案。 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.
欢呼。
Something like this: 像这样的东西:
Parallel.For(0, folder.Items.Count - 1, delegate(int i) {
object item = folder.Items[i];
});
Or with ForEach: 或者使用ForEach:
Parallel.ForEach(folder.Items, item => {whatever you want to do with item})
Note: folder.Items has to be implementing IEnumerable 注意:folder.Items必须实现IEnumerable
Assuming that this is correct 假设这是正确的
foreach (Object item in folder.Items)
Process(item);
then it changes to 然后它变成了
Parallel.ForEach (folder.Items, item => Process(item));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.