0

我撞到了另一面墙。请在此处查看我之前关于多线程和 SMTP 的问题

无论如何,我试图在运行时动态创建线程并调用 Start() 方法,但收到 KeyNotFoundException。对此的任何见解将不胜感激。如果我的代码不在这里,基本上我希望完成的是根据用户输入(计数)创建一个在单个线程上运行的唯一 SMTP 实例,并同时运行每个线程。

//count is user input (number of messages)  

int instanceCount = 0;

        var vartable = new Dictionary<string, SmtpClient>();
        var vartable2 = new Dictionary<string, Thread>();

        for (int i = 0; i < count; ++i)
        {
            vartable[instanceCount.ToString()] = new SmtpClient
            {
                Host = txtBxSenderHost.Text,
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(strSenderAddress, strSenderPassword)
            };

            vartable2[instanceCount.ToString()] = new Thread(delegate()
            {
                using (var message = new MailMessage(senderAdrress, toAddress)
                {
                    Subject = strSubject,
                    Body = strBody
                })

                {
                    {
                        ((SmtpClient)vartable[instanceCount.ToString()]).Send(message);
                    }
                }
            });

            instanceCount++;
        }

只是为了测试,我用“0”来查看是否工作

        vartable2["0"].Start();
4

1 回答 1

2

当您在委托内存储循环变量时,您需要在委托外声明一个单独的变量,以避免接收到迭代的最后一个值。

如果您进行打印语句,您将看到每个线程试图访问的值都是相同的,无论 count 的值是多少。只需在委托语句上方添加一个变量:

        int tempInstanceCount = instanceCount;
        vartable2[instanceCount.ToString()] = new Thread(delegate()
        {
            using (var message = new MailMessage(senderAdrress, toAddress)
            {
                Subject = strSubject,
                Body = strBody
            })

            {
                {
                    ((SmtpClient)vartable[tempInstanceCount.ToString()]).Send(message);
                }
            }
        });
于 2013-01-25T22:23:41.257 回答