将 foreach 循环更改为 Parallel.ForEach 循环
好的,这是基本背景。该程序连接到 Outlook/Exchange 并解析所有邮件消息以查看哪些邮件已加密。我想做的一件事是使用多线程来减少扫描消息所需的时间。
目前代码如下所示:
foreach (Object item in folder.Items) {
//Checks for encryption and gets needed info and updates count
}
我想改用 Parallel.ForEach 函数。我想知道如何设置它。我尝试将表达式设置为现在的样子,但收到一条错误消息,指出对象类型正在用作变量。任何对此的帮助将不胜感激。
好的,我给出的布局似乎是正确的。代码现在看起来像这样:
Parallel.ForEach(folder.Items, item =>
{
//does stuff
});
我现在收到以下错误:
错误 15 方法的类型参数 System.Threading.Tasks.Parallel.ForEach(System.Collections.Concurrent.OrderablePartitioner, 系统.操作)' 无法从用法推断。尝试指定类型参数 明确地。
有什么想法吗?感谢你们的帮助,非常感谢。
好的,我找到了这个网站:http://blogs. msdn.com/b/pfxteam/archive/2010/03/02/9971804.aspx 它给了我该错误所需的答案。我只需要通过创建一个转换函数将集合更改为通用集合。
static IEnumerable<object> Cast(IEnumerable source)
{
foreach (object o in source)
yield return o;
}
然后将原来的调整到
Parallel.ForEach(Cast(folder.Items), item =>
{
//does stuff
});
现在它运行没有错误。欢呼。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这样的东西:
或者使用 ForEach:
注意:folder.Items 必须实现 IEnumerable
Something like this:
Or with ForEach:
Note: folder.Items has to be implementing IEnumerable
假设这是正确的
,那么它会变成
Assuming that this is correct
then it changes to