您好,感謝您提前爲您出謀劃策,查找平行的ForEach線程拋出異常
我有一個並行for每個散發出大量電子郵件循環。我想知道的是如何找出哪個線程拋出SmtpException。我想知道它無法發送到哪個電子郵件地址。
protected void btnSend_Click(object sender, EventArgs e)
{
try
{
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;
//for (int i = 0; i < emailList.Count; i++)
//{
// if (emailList[i].Contains('<'))
// {
// if (!Mail.IsValidEmailAddress(emailList[i].ToString().Split('<')[1].Replace(">", ""), PortalId))
// {
// emailList.RemoveAt(i);
// invalidList.Add(emailList[i].ToString());
// }
// }
// else
// {
// if (!Mail.IsValidEmailAddress(emailList[i].ToString(), PortalId))
// {
// emailList.RemoveAt(i);
// invalidList.Add(emailList[i].ToString());
// }
// }
//}
Parallel.ForEach(emailList, email =>
{
Mail.SendMail(tbEmailFrom.Text, email.ToString(), tbEmailCC.Text, tbEmailBC.Text, tbReplyTo.Text, DotNetNuke.Services.Mail.MailPriority.Normal,
tbSubject.Text, MailFormat.Html, System.Text.Encoding.UTF8, tbEmailBody.Text, attachments, smtpServer, smtpAuthentication, smtpUsername, smtpPassword, false);
Interlocked.Increment(ref count);
});
RadRadialGauge1.Pointer.Value = count;
}
if (rbListType.Items.FindByValue("Excel").Selected)
{
emailList = tbEmailTo.Text.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
int count = 0;
int total = emailList.Count;
RadRadialGauge1.Scale.Max = total;
RadRadialGauge1.Scale.Min = 0;
//for (int i = 0; i < emailList.Count; i++)
//{
// if (emailList[i].Contains('<'))
// {
// if (!Mail.IsValidEmailAddress(emailList[i].ToString().Split('<')[1].Replace(">", ""), PortalId))
// {
// emailList.RemoveAt(i);
// invalidList.Add(emailList[i].ToString());
// }
// }
// else
// {
// if (!Mail.IsValidEmailAddress(emailList[i].ToString(), PortalId))
// {
// emailList.RemoveAt(i);
// invalidList.Add(emailList[i].ToString());
// }
// }
//}
Parallel.ForEach(emailList, email =>
{
Mail.SendMail(tbEmailFrom.Text, email.ToString(), tbEmailCC.Text, tbEmailBC.Text, tbReplyTo.Text, DotNetNuke.Services.Mail.MailPriority.Normal,
tbSubject.Text, MailFormat.Html, System.Text.Encoding.UTF8, tbEmailBody.Text, attachments, smtpServer, smtpAuthentication, smtpUsername, smtpPassword, false);
Interlocked.Increment(ref count);
});
RadRadialGauge1.Pointer.Value = count;
}
throw new SmtpException();
}
}
catch (SmtpException smtp)
{
RadRadialGauge1.Pointer.Value = RadRadialGauge1.Pointer.Value - 1;
var email = smtp.
Exceptions.LogException(smtp);
}
catch (Exception ex)
{
Exceptions.LogException(ex);
}
}
你有沒有想過用'try-catch'封裝調用? –
我正在使用Try-Catch? – JohnCoderMan
如何:處理並行循環中的異常 (https://msdn.microsoft.com/en-us/library/Dd460695(v=VS.110).aspx) – MrDywar