好的,这是基本背景。该程序连接到 outlook/exchange 并解析所有邮件消息以查看哪些是加密的。我想做的一件事是使用多线程来减少扫描消息所需的时间。
目前代码如下所示:
foreach (Object item in folder.Items) {
//Checks for encryption and gets needed info and updates count
}
我想改用 Parallel.ForEach 函数。我想知道如何设置它。我尝试将表达式设置为现在的样子,但我收到一条错误消息,指出 Object 类型正被用作变量。如有任何帮助,我们将不胜感激。
好的,我得到的布局似乎是正确的。代码现在看起来像这样:
Parallel.ForEach(folder.Items, item =>
{
//does stuff
});
我现在收到以下错误:
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.
有什么想法吗?感谢您的帮助,非常感谢。
好的,我找到了这个网站: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
});
现在它运行没有错误。欢呼吧。
最佳答案
像这样:
Parallel.For(0, folder.Items.Count - 1, delegate(int i) {
object item = folder.Items[i];
});
或者使用 ForEach:
Parallel.ForEach(folder.Items, item => {whatever you want to do with item})
注意:folder.Items 必须实现 IEnumerable
关于c# - 将 foreach 循环更改为 Parallel.ForEach 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8217350/