C# 将foreach循环更改为Parallel.foreach循环
好的,这是基本背景。此程序连接到outlook/exchange并解析所有邮件,以查看哪些邮件已加密。我想做的事情之一是使用多线程来减少扫描消息所需的时间 当前代码如下所示:C# 将foreach循环更改为Parallel.foreach循环,c#,parallel.foreach,C#,Parallel.foreach,好的,这是基本背景。此程序连接到outlook/exchange并解析所有邮件,以查看哪些邮件已加密。我想做的事情之一是使用多线程来减少扫描消息所需的时间 当前代码如下所示: foreach (Object item in folder.Items) { //Checks for encryption and gets needed info and updates count } Parallel.For(0, folder.Items.Count - 1, delegate(int i)
foreach (Object item in folder.Items) {
//Checks for encryption and gets needed info and updates count
}
Parallel.For(0, folder.Items.Count - 1, delegate(int i) {
object item = folder.Items[i];
});
我想改用Parallel.ForEach函数。我在想我怎样才能把它设置好。我尝试将表达式设置为现在的状态,但出现一个错误,指出对象类型正在用作变量。在此方面的任何帮助都将不胜感激
好的,我得到的布局似乎是正确的。现在代码如下所示:
Parallel.ForEach(folder.Items, item =>
{
//does stuff
});
我现在得到以下错误:
错误15方法的类型参数无效
System.Threading.Tasks.Parallel.ForEach(System.Collections.Concurrent.OrderablePartitioner,
系统(行动)'
无法从用法推断。尝试指定类型参数
明确地说
有什么想法吗?谢谢你们的帮助,非常感谢
好的,我找到了这个网站:它给了我错误的答案。我只需要通过创建一个casting函数将集合更改为通用集合
static IEnumerable<object> Cast(IEnumerable source)
{
foreach (object o in source)
yield return o;
}
现在它运行没有错误。万岁。诸如此类:
foreach (Object item in folder.Items) {
//Checks for encryption and gets needed info and updates count
}
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})
注意:文件夹。项目必须实现IEnumerable,假设这是正确的
foreach (Object item in folder.Items)
Process(item);
然后它变成了
Parallel.ForEach (folder.Items, item => Process(item));
请发布修改后的代码(给出错误消息的代码)。编辑后:它现在取决于
文件夹。Items
和/或//does stuff
+1也提到了实现IEnumerable的要求。@ericj:这是从for(Items in Items)…