Jak wywołać metodę asynchronicznie
Próbowałem podążać za tym linkiemPołączenie asynchroniczne ale niektóre klasy są przestarzałe.
Chcę więc dokładną odpowiedź na mój projekt.
<code>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; } } } </code>
Proszę spojrzeć naRegister
metoda. Po zapisaniu danych nie chcę czekać na wysłanie poczty. Jeśli to możliwe, chcę przetworzyć wysyłkę poczty w innym wątku, aby użytkownik nie czekał dłużej.
Nie muszę wiedzieć, czy poczta została wysłana pomyślnie.
Mam nadzieję, że zrozumiesz o co mi chodzi. Przepraszam za mój zły język angielski.