如何从我的应用程序发送电子邮件时,我避免延误? [英] How do I avoid a delay when sending email from my application?
问题描述
我有一个小型控制台应用程序。它检查一些设置,使得一些决定,并发送电子邮件。问题是邮件实际上并没有被发送到我的应用程序完成。我希望电子邮件尽快送我的方法发送电子邮件完成。
I have a small console application. It checks a few settings, makes some decisions, and sends an email. The problem is the email doesn't actually get sent until my application finishes. I want the email sent as soon as my method that sends the email completes.
起初,我刚刚创建了一个MailMessage,并呼吁。发送()。这时候,我发现邮件没有被发送,直到程序完成。
Initially, I just created a MailMessage and called .Send(). That's when I noticed the mail was not being sent until the app finished.
然后我试图使用任务并行库。
Then I tried using the task parallel library.
var taskA = Task.Factory.StartNew(() => msg.Send());
同样,消息不会被发送到我的整个应用程序完成。
Again, the messages don't get sent until my entire application finishes.
如何在msg.send执行,我发了封邮件而不是应用程序完成时?
How do I sent an email when msg.send executes, not when the app completes?
谢谢!
推荐答案
SmptClient
支持异步通过发送邮件 SendAsync
,但是在Web应用程序实际上这挂起的请求线程。
SmptClient
supports async sending of mail via SendAsync
, however in practice in a web application this hangs the request thread.
要避免阻塞我推荐使用线程池
来断火在后台线程中的电子邮件。这不会阻止你的应用程序。
To avoid blocking I recommend using the ThreadPool
to fire off the email in a background thread. This won't block your application.
ThreadPool.QueueUserWorkItem(o => {
using (SmtpClient client = new SmtpClient(...))
{
using (MailMessage mailMessage = new MailMessage(...))
{
client.Send(mailMessage, Tuple.Create(client, mailMessage));
}
}
});
这篇关于如何从我的应用程序发送电子邮件时,我避免延误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!