Creating manual threads - but getting duplicate threads

前端 未结 2 1713
离开以前
离开以前 2021-01-23 16:38

ISSUE: Getting duplicate items, i.e more threads are getting created than the array size... Hi Folks, I am creating thread in the loop for each element of array. The real use i

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-23 17:26

    I don't like that your threads share the same variables (I mean n and amazonMessageID), it is not thread safe and it may cause your problem. Moreover I suggest you to use Parallel.ForEach method, it can make your code easy. It could look like this:

    try
    {
    
         Parallel.ForEach(arrMessageid.Distinct(),
             n => 
             {
                 try
                 {
                     var amazonMessageID = SendSimpleEmail_Part2(messageAmazonRequestBatch.ElementAt(n).req);
                     messageAmazonRequestBatch.ElementAt(n).msg.AmazonMessageID = amazonMessageID;
                     logManager_MessageLogwithAmazonmsgID.LogMessage(",\t" + n , true);
                 }
                 catch (Exception ex)
                 {
                     logManager_RunSummary.LogMessage(ex.Message, true); 
                 }
             }
          );              
    
    }
    catch (Exception ex)
    {
        logManager_RunSummary.LogMessage(ex.Message, true);
    }
    

提交回复
热议问题