我试过关注这个链接异步调用,但有些类已经过时了。
所以我想为我的项目提供一个准确的答案。
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; }
}
}
请看Register
方法。保存数据后,我不想等待发送邮件。如果可能的话,我想在其他线程上处理邮件的发送,这样用户就不会等待更长的时间。
我不需要知道邮件是否发送成功。
希望你能明白我的意思。对不起,我的英语不好。