I’ve tried following this link Asynchronous call but some classes are obsolete.
So I want an exact answer for my project.
public class RegisterInfo
{
public bool Register(UserInfo info)
{
try
{
using (mydatabase db = new mydatabase())
{
userinfotable uinfo = new userinfotable();
uinfo.Name = info.Name;
uinfo.Age = info.Age;
uinfo.Address = info.Address;
db.userinfotables.AddObject(uinfo);
db.SaveChanges();
// Should be called asynchronously
Utility.SendEmail(info); // this tooks 5 to 10 seconds or more.
return true;
}
}
catch { return false; }
}
}
public class UserInfo
{
public UserInfo() { }
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
public class Utility
{
public static bool SendEmail(UserInfo info)
{
MailMessage compose = SomeClassThatComposeMessage(info);
return SendEmail(compose);
}
private static bool SendEmail(MailMessage mail)
{
try
{
SmtpClient client = new SmtpClient();
client.Host = "smtp.something.com";
client.Port = 123;
client.Credentials = new System.Net.NetworkCredential("username@domainserver.com", "password");
client.EnableSsl = true;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
client.Send(mail);
return true;
}
catch { return false; }
}
}
Please look at the Register method.
After saving the data, I don’t want to wait for the sending of mail. If possible I want to process the sending of mail on other thread so the user will not wait for a longer time.
I don’t need to know if mail has sent successfully.
Hope you could understand what I mean. Sorry for my bad English.
Using
Thread:Using
ThreadPool:Using
Task:Of course
ThreadandThreadPoolrequireusing System.ThreadingwhileTaskrequiresusing System.Threading.TasksAs stated by David Anderson, SmtpClient already supports asynchronous send (I probably should have paid attention to the content of the function rather than answering the question), so technically you could just use that to handle the send though it won’t offload the processing of your entire method.