暂停Parallel.For循环

时间:2015-09-14 18:09:57

标签: c# asp.net parallel-processing

我有一个嵌套的Parallel.ForParallel.ForEach循环,它会向电子邮件发送电子邮件。该列表可能超过10000封电子邮件 - 所以我决定将列表分成几部分并发送。但是我希望能够在每次Parallel.For次迭代后暂停。我找了一条路 - 却无处可去。

if (Page.IsValid)
            {
                List<string> emailList;
                List<string> invalidList = new List<string> { };
                string[] attachments = { };
                if (rbListType.Items.FindByValue("CSV").Selected)
                {
                    emailList = tbEmailTo.Text.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
                    int count = 0;
                    int total = emailList.Count;
                    RadRadialGauge1.Scale.Max = total;
                    RadRadialGauge1.Scale.Min = 0;
                    var errorList = new ConcurrentBag<string>();
    var chunk = emailList
        .Select((value, index) => new { Index = index, Value = value })
        .GroupBy(x => x.Index / 2)
        .Select(g => g.Select(x => x.Value).ToList())
        .ToList();



    Parallel.For(0, chunk.Count, i =>
    {
        Parallel.ForEach(chunk[i], email =>
        {
            try
            {
                MailMessage em = new MailMessage();
                em.From = new MailAddress(tbEmailFrom.Text);
                em.To.Add(email.ToString());

                if (!String.IsNullOrEmpty(tbEmailCC.Text))
                {
                    em.CC.Add(tbEmailCC.Text);
                }

                if (!String.IsNullOrEmpty(tbEmailBC.Text))
                {
                    em.Bcc.Add(tbEmailBC.Text);
                }

                em.ReplyToList.Add(tbReplyTo.Text);
                em.Body = tbEmailBody.Text;
                em.IsBodyHtml = true;
                em.Subject = tbSubject.Text;
                em.Priority = System.Net.Mail.MailPriority.Normal;
                em.BodyEncoding = System.Text.Encoding.UTF8;
                SmtpClient sm = new SmtpClient();

                if (String.IsNullOrEmpty(smtpServer))
                {
                    sm.Host = Host.SMTPServer;
                }
                else
                {
                    sm.UseDefaultCredentials = false;
                    sm.Host = smtpServer;
                    sm.Credentials = new System.Net.NetworkCredential(smtpUsername, smtpPassword);
                }

                sm.Send(em);
                Interlocked.Increment(ref count);
            }
            catch (SmtpException smtp)
            {
                errorList.Add(email.ToString() + "<br />");
            }
        });  
     });

0 个答案:

没有答案
相关问题