异步发送的电子邮件在C#中? [英] Asynchronously sending Emails in C#?
问题描述
我正在开发,其中用户点击/ presses在一个窗口中的某个按钮输入的应用程序,该应用程序做了一些检查,确定是否要发送几封电子邮件,或没有,然后显示与另一个窗口一个消息。
I'm developing an application where a user clicks/presses enter on a certain button in a window, the application does some checks and determines whether to send out a couple of emails or not, then show another window with a message.
我的问题是,发送的电子邮件2减缓显着的过程中,对于一些(〜8)秒的第一个窗口看起来冻结,同时它做的发送。
My issue is, sending out the 2 emails slows the process noticeably, and for some (~8) seconds the first window looks frozen while it's doing the sending.
有什么办法,我可以有这些邮件的背景发送并显示下一个窗口,对吗?
Is there any way I can have these emails sent on the background and display the next window right away?
请不要限制与使用的是X班或只是使用的是X方法,因为我不是太有语言又熟悉和一些更多的信息将是非常美联社preciated你的答案。
Please don't limit your answer with "use X class" or "just use X method" as I am not all too familiarized with the language yet and some more information would be highly appreciated.
感谢。
推荐答案
由于.NET 4.5 SmtpClient的实现异步awaitable方法
<一href=\"http://msdn.microsoft.com/en-us/library/hh193922%28v=vs.110%29.aspx\"><$c$c>SendMailAsync$c$c>.
其结果是,以异步发送电子邮件是如下:
As of .NET 4.5 SmtpClient implements async awaitable method
SendMailAsync
.
As a result, to send email asynchronously is as following:
public async Task SendEmail(string toEmailAddress, string emailSubject, string emailMessage)
{
var message = new MailMessage();
message.To.Add(toEmailAddress);
message.Subject = emailSubject;
message.Body = emailMessage;
using (var smtpClient = new SmtpClient())
{
await smtpClient.SendMailAsync(message);
}
}
这篇关于异步发送的电子邮件在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!