c# - 在 foreach 循环中创建的同一线程正在执行多次
问题描述
我正在循环中的 foreach 报告列表中创建线程。创建的每个线程都将调用其 DLL,将报告数据插入到数据库中。问题是创建的每个线程都在执行多次插入重复数据。如何避免在 foreach 循环中多次执行相同的线程?
下面是我的代码: 每个报告都通过线程调用 DLL 方法
foreach (ReportGeneric.ExportReportSchedulerModel report in reportList)
{
log.Debug(report.ReportName + " Export():");
var parametersArray = new object[1];
parametersArray[0] = report;
log.Debug("Thread started in ExportReport() for " + report.ReportName);
Thread exporttoexcel = new Thread(() =>
{
_isStarted = false;
//invoking DLL method
var ret = ReportInvokeFunction(moduleName: report.ReportName.Split('_')[0], className: report.ReportName, functionName: "SelectData", parameters: parametersArray);
if (ret > 0)
{
log.Debug("ExportReport() successfull " + report.ReportName);
_isStarted = true;
}
else
{
log.Error("ExportReport() failed " + report.ReportName);
_isStarted = false;
}
});
exporttoexcel.Start();
}
以下是为其中一份报告编写的日志:如下所示,同一线程 [45] 在 2018-07-27 13:35:05,781 的同一时间执行了两次。这是在数据库中创建重复数据。
2018-07-27 13:35:05,781 [45] DEBUG ReportGeneric.GenericReportBase - ---- 开始阅读:IvrHostTransactionReport 从 20180727 133005 到 20180727 133505:
2018-07-27 13:35:05,781 [45] 调试 IvrHostTransactionReport.IvrHostTransactionReport - ---- 开始从 SP 获取数据:IvrHostTransactionReport 从 20180727 133005 到 20180727 133505:
2018-07-27 13:35:05,781 [42] DEBUG ReportGeneric.GenericReportBase - ---- 开始阅读:ChatInteractionReport 从 20180727 133005 到 20180727 133505:
2018-07-27 13:35:05,781 [42] DEBUG ChatInteractionReport.ChatInteractionReport - ---- 开始从 SP 获取数据:ChatInteractionReport 从 20180727 133005 到 20180727 133505:
解决方案
线程应该是相互独立的内存,你不能在线程内部使用“report”变量
foreach(report){
ReportGeneric.ExportReportSchedulerModel tempReport = report; // independent memory address
Thread exporttoexcel = new Thread(() => {
.....
tempReport ....
.....
});
exporttoexcel.Start();
}
推荐阅读
- python - 将String转换为二进制格式并展开二进制文件
- css - 具有 `max-width` 和 `max-height` 的 Flex 项目会导致其旁边的文本在 Chrome 中不必要地中断
- google-chrome - 在赛普拉斯中,如何强制下载 PDF 文件而不是在新选项卡中打开?
- json - get_json_object spark 实用程序函数中的美元符号是什么意思?
- c++ - 是否允许打印悬空引用的地址?
- android - android studio重建错误:找不到Gradle任务来构建为什么?
- c# - Visual Studio IDE Helper/Summary - 通过构造函数传递对象的引用名称
- c# - ASP.Net Core:如何获取无效 ModelState 值的键?
- c++ - 如何调试clang C++ 编译器错误?(clang 前端命令失败,退出代码 139)
- javascript - Reactjs - 我的 redux 没有存储用户