末我有这个问题,当我跑是这样的:Parallel.ForEach行为像一个普通的每个朝向的迭代
Parallel.ForEach(dataTable.AsEnumerable(), row =>
{
//do processing
}
假设有500+的记录说,870一旦并行.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);
});
});
请提供完整的代码块 – 2011-02-02 19:30:06
我不知道这应该是一个评论,或一个答案,但我觉得它需要指出:`DataTable`不是线程安全的类型。因此,如果你的'//处理'代码涉及任何类型的修改(甚至包括单个行内的单元格),恐怕你正在寻求一个痛苦的世界。 – 2011-02-02 19:31:52
对于dataTable中的每一行,都会调用数据库获取数据并将其加载到文件中。它像一个提取过程。从数据库提取数据并提取到文件。 – 2011-02-02 19:36:31