Creating manual threads - but getting duplicate threads

ⅰ亾dé卋堺 提交于 2019-12-02 05:11:35

Your lambda expression is capturing the loop variable n, so when your lambda executes, the value of n has already changed; you need to copy n to a local variable inside the loop. (assuming you're using C# 4 or earlier; C# 5 fixed that problem).

Another issue is that all your threads use the same amazonMessageID variable; you should declare it inside the lambda expression instead.

            foreach (int n in arrMessageid)
            {
                int n2 = n;
                thrdSendEmail = new Thread(() =>
                {
                        try
                        {
                            string amazonMessageID = SendSimpleEmail_Part2(messageAmazonRequestBatch.ElementAt(n2).req);
                            messageAmazonRequestBatch.ElementAt(n2).msg.AmazonMessageID = amazonMessageID;
                            logManager_MessageLogwithAmazonmsgID.LogMessage(",\t" + n2 , true);
                            //logManager_MessageLogwithAmazonmsgID.LogMessage(",\t" + n2 + ",\t" + messageAmazonRequestBatch.ElementAt(n2).msg.QueueMessageId + ",\t" + amazonMessageID, true);
                        }
                        catch (Exception ex) { logManager_RunSummary.LogMessage(ex.Message, true); }                                
                });
 ...

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!