Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method asynchronously

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("[email protected]", "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.

like image 255
fiberOptics Avatar asked Dec 01 '22 23:12

fiberOptics


1 Answers

Using Thread:

new Thread(() => Utility.SendEmail(info)).Start();

Using ThreadPool:

ThreadPool.QueueUserWorkItem(s => Utility.SendEmail(info));

Using Task:

Task.Factory.StartNew(() => Utility.SendEmail(info));

Of course Thread and ThreadPool require using System.Threading while Task requires using System.Threading.Tasks


As 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.

like image 118
M.Babcock Avatar answered Dec 20 '22 06:12

M.Babcock