Creating manual threads - but getting duplicate threads

前端 未结 2 1688
离开以前
离开以前 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

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

提交回复
热议问题