【发布时间】:2015-07-01 03:05:45
【问题描述】:
我在 DTable 中实现 Parallel.ForEach 时遇到问题。以下是我正在实现的示例代码:
Parallel.ForEach(dTable4.AsEnumerable(), row4 =>
{
string getCondition = row4[1].ToString();
getCondition = EvaluateCondExpression(getCondition); //Evaluates CM for value (CM1==2 && CM2<5);
Expression e = new Expression(getCondition); //getCondition = (2==2 && 2<5)
var evalutateCondition = e.Evaluate();
if (Convert.ToBoolean(evalutateCondition))
{
//Write string to TextBox
}
}
当我运行它时,线程没有得到有效管理,而且它比 foreach 循环花费的时间太长。 从 GUI 组合框和 numericUpDown 检查用户提供的参数后,EvaluateCondExpression 函数返回值
private string EvaluateCondExpression(string getCondition)
{
string[] splitgetCondition1 = SeprateCharacter(getCondition);
foreach (string oneCondition in splitgetCondition1)
{
string conditionValue = oneCondition;
if (oneCondition.Contains("CM"))
{
conditionValue = RemoveMultipleChar(conditionValue.Replace('!', ' ').Trim());
string getInputNumber = getTableOneInputNo(conditionValue, dTable1);
string tableOneValue = checkComboxValue(m_comboBox, getInputNumber);
getCondition = getCondition.Replace(conditionValue, tableOneValue);
}
}
return getCondition;
}
串行 ForEach 计算花费了太多时间,所以我想应用 Parallel.ForEach 迭代,但不幸的是它不起作用。谁能建议我如何最大限度地提高性能以及我在 Parallel.ForEach 中做错了什么。
【问题讨论】:
-
您可能会看到通过使用传统的 foreach 将每次迭代包装在一个任务中来提高性能。将每次迭代的任务添加到集合中,然后在 foreach 调用之外添加
Task.WhenAll(tasks);,如果有的话,它会让您能够等待昂贵的并行进程。 -
你能给我提供任何参考链接吗?
-
参考显示性能改进?或链接显示这样做的例子?
-
将每个迭代包装在一个任务中的参考。
-
对于长时间运行的任务,超过 2-3 秒的任务可以考虑使用 Async - Await,而不是 Parallel.ForEach。 Infact Async - Await 甚至不像并行调用那样阻塞
标签: c# foreach datatable parallel-processing parallel.foreach