如何异步调用方法

fib*_*ics 4 c# asynchronous

我试过跟这个链接异步调用,但有些类已经过时了.
所以我想为我的项目准确回答.

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; }
    }
}    
Run Code Online (Sandbox Code Playgroud)

请看Register方法.保存数据后,我不想等待发送邮件.如果可能的话,我想处理在其他线程上发送邮件,这样用户就不会等待更长的时间.
我不需要知道邮件是否已成功发送.
希望你能明白我的意思.对不起,我的英语不好.

M.B*_*ock 13

使用Thread:

new Thread(() => Utility.SendEmail(info)).Start();
Run Code Online (Sandbox Code Playgroud)

使用ThreadPool:

ThreadPool.QueueUserWorkItem(s => Utility.SendEmail(info));
Run Code Online (Sandbox Code Playgroud)

使用Task:

Task.Factory.StartNew(() => Utility.SendEmail(info));
Run Code Online (Sandbox Code Playgroud)

当然ThreadThreadPool要求using System.Threading,同时Task要求using System.Threading.Tasks


正如David Anderson所说,SmtpClient已经支持异步发送 (我可能应该注意函数的内容而不是回答问题),所以从技术上讲,你可以使用它来处理发送,尽管它不会卸载处理你的整个方法.

  • Lambda上瘾者 - > (4认同)