1

I am creating threads inside foreach report list in the loop. Each thread created will invoke its DLL where the report data is inserted into the database. Problem is that each thread created is executing multiple times inserting duplicate data. How can I avoid these multiple executions of same threads in foreach loop?

Below is my code : Each report is passed through the thread to call DLL method

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();
}

Below is the logs are written for one of the reports: As seen below same thread [45] is executed twice at same time 2018-07-27 13:35:05,781. This is creating duplicate data in the database.

2018-07-27 13:35:05,781 [45] DEBUG ReportGeneric.GenericReportBase - ---- Started reading : IvrHostTransactionReport from 20180727 133005 to 20180727 133505:

2018-07-27 13:35:05,781 [45] DEBUG IvrHostTransactionReport.IvrHostTransactionReport - ---- Started fetching data from SP : IvrHostTransactionReport from 20180727 133005 to 20180727 133505:

2018-07-27 13:35:05,781 [42] DEBUG ReportGeneric.GenericReportBase - ---- Started reading : ChatInteractionReport from 20180727 133005 to 20180727 133505:

2018-07-27 13:35:05,781 [42] DEBUG ChatInteractionReport.ChatInteractionReport - ---- Started fetching data from SP : ChatInteractionReport from 20180727 133005 to 20180727 133505:

Community
  • 1
  • 1
Shreenitha
  • 189
  • 8

1 Answers1

0

Threads should be memory independent from each other, you can not use "report" variable inside the threads

foreach(report){
     ReportGeneric.ExportReportSchedulerModel tempReport = report; // independent memory address
     Thread exporttoexcel = new Thread(() => {
          .....
          tempReport ....
          .....
     });
     exporttoexcel.Start();
}
  • 1
    Thank you :) This makes sense as the report parameter is being changed when it goes to next loop before starting Thread. So assigning it to temp variable internally will create new instance. – Shreenitha Sep 06 '18 at 10:59