eMail from asp.net c# program very slow
I am sending a simple email message from an asp.net web page to two recipients. It's taking about 15 seconds to finish execution. Is it possible to speed this up? This is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
namespace NihulKriotNS.BLL
{
public class EMailClass
{
//fields
private const string strFrom = "myEmail";
private const string mailServer = "myServer";
private const string userName = "myUserName";
private const string usePass = "myPassword";
//ctors
public EMailClass()
{
}
public void SendEMail(List<string> emailList, string strSubject, string strMessage, bool isHTML)
开发者_StackOverflow中文版 {
MailMessage msg = new MailMessage();
msg.From = new MailAddress(strFrom);
if (emailList != null && emailList.Count > 0 )
foreach (string em in emailList)
{
msg.To.Add(em);
}
else
return;
msg.Subject = strSubject;
msg.Body = strMessage;
msg.IsBodyHtml = isHTML;
SmtpClient smtp = new SmtpClient(mailServer);
smtp.Credentials = new System.Net.NetworkCredential(userName, usePass);
smtp.Send(msg);
msg.Dispose();
}
}
}
I tried using smpt.SendAsync but didn't help at all. I'm not realy sure how to use it properly. Thank you very much.
Earlier I received an answer from Samir Adel (and confirmed in a comment by someone else I don't remember who) to use multiple threads. For some reason, unfortunately, this answer has deleted. I wasn't familiar with the subject of threading. I looked up the subject in the book Pro C# 2008 and the .NET 3.5 Platform by Andrew Troelsen. I came up with the following code:
Thread backgroundThread = new Thread(new ThreadStart(EMailPrepareAndSend));
backgroundThread.Name = "Secondary";
backgroundThread.Start();
Where EMailPrepareAndSend is a method where the email message is prepared and from which the SendEmail() method in the EMail class, shown in my question, is called. This has enabled the program to continue immediately even tho the email has not finished being sent. Thank you to Samir Adel, his response got me in the right direction.
精彩评论