【问题标题】:Same thread created inside foreach loop is executing multiple times [duplicate]在 foreach 循环中创建的同一线程正在执行多次[重复]
【发布时间】:2018-07-27 06:13:31
【问题描述】:

我正在循环中的 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] DEBUG 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:

【问题讨论】:

  • 这两行是完全不同的IMO,readingfetching也不一样吧?

标签: c# multithreading model-view-controller foreach threadpool


【解决方案1】:

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

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

【讨论】:

  • 谢谢 :) 这是有道理的,因为在启动 Thread 之前进入下一个循环时报告参数正在更改。因此在内部将其分配给 temp 变量将创建新实例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-16
  • 2016-04-09
  • 1970-01-01
相关资源
最近更新 更多