【发布时间】:2011-02-02 19:27:35
【问题描述】:
当我运行这样的事情时遇到了这个问题:
Parallel.ForEach(dataTable.AsEnumerable(), row =>
{
//do processing
}
假设有 500 多条记录说 870。一旦 Parallel.ForEach 完成 850,它似乎是按顺序运行的,即一次只有 1 个操作。它非常快地完成了 850 次操作,但是当它接近迭代结束时,它变得非常慢,并且似乎每个操作都像常规操作一样执行。我什至尝试了 2000 条记录。
我的代码有问题吗?请提出建议。
下面是我正在使用的代码
抱歉,我刚刚发布了错误的示例。这是正确的代码:
Task newTask = Task.Factory.StartNew(() =>
{
Parallel.ForEach(dtResult.AsEnumerable(), dr =>
{
string extractQuery = "";
string downLoadFileFullName = "";
lock (foreachObject)
{
string fileName = extractorConfig.EncodeFileName(dr);
extractQuery = extractorConfig.GetExtractQuery(dr);
if (string.IsNullOrEmpty(extractQuery)) throw new Exception("Extract Query not found. Please check the configuration");
string newDownLoadPath = CommonUtil.GetFormalizedDataPath(sDownLoadPath, uKey.CobDate);
//create folder if it doesn't exist
if (!Directory.Exists(newDownLoadPath)) Directory.CreateDirectory(newDownLoadPath);
downLoadFileFullName = Path.Combine(newDownLoadPath, fileName);
}
Interlocked.Increment(ref index);
ExtractorClass util = new ExtractorClass(SourceDbConnStr);
util.LoadToFile(extractQuery, downLoadFileFullName);
Interlocked.Increment(ref uiTimerIndex);
});
});
【问题讨论】:
-
请提供完整的代码块
-
我不确定这应该是评论还是答案,但我觉得需要指出:
DataTable不是线程安全类型。因此,如果您的//do processing代码涉及任何类型的修改(即使是对单个行中的单元格),恐怕您是在要求一个痛苦的世界。 -
好的,对于 dataTable 中的每一行,它将调用数据库获取数据并将其加载到文件中。它就像一个提取过程。从数据库中获取数据并提取到文件中。
-
@bunny 当你说它似乎是按顺序运行时,你有什么证据证明这一点?例如,您是否打印出线程 ID 以获得粗略的感觉?
-
@bunny 提示 在回复 cmets 时包含 @usernames,该用户将收到通知。干杯,千叶。
标签: c# multithreading c#-4.0 parallel-processing task-parallel-library