首页 > 解决方案 > 在 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:

标签: c#multithreadingmodel-view-controllerforeachthreadpool

解决方案


线程应该是相互独立的内存,你不能在线程内部使用“report”变量

foreach(report){
     ReportGeneric.ExportReportSchedulerModel tempReport = report; // independent memory address
     Thread exporttoexcel = new Thread(() => {
          .....
          tempReport ....
          .....
     });
     exporttoexcel.Start();
}

推荐阅读