简体   繁体   English

运行后台任务以在用户发布到ASP.NET CORE中的讨论区时发送电子邮件

[英]Running a background task for sending emails when a user posts to a discussion board in ASP.NET CORE

I need to send emails via SMTP to all subscribers of a discussion board. 我需要通过SMTP向讨论板的所有订户发送电子邮件。 If there a lot (say 1000+) subscribers, I do not want the users who posts a new post to have to wait while the notification emails are being sent out. 如果有很多订户(例如1000多个),我不希望发布新帖子的用户在发送通知电子邮件时必须等待。

At first I thought I could use: System.Net.Mail.SmtpClient.SendMailAsync 起初我以为我可以使用: System.Net.Mail.SmtpClient.SendMailAsync

But, as this post explains , "Async is not a magic wand that makes the action return the response quicker. Your task (in this case, sending an email) takes as long as it takes and async or not, the action will not return a response until the task has completed." 但是,正如这篇文章所解释的那样“异步并不是使操作更快返回响应的魔杖。您的任务(在这种情况下,发送电子邮件)需要花费的时间,无论是否同步,操作都不会返回直到任务完成为止。” Async is more about being efficient with threads than it is about making a task run faster. 异步更多地是关于提高线程的效率,而不是使任务更快地运行。

First, is my research about SendMailAsync correct? 首先,我对SendMailAsync的研究正确吗? I don't think it is a correct solution. 我认为这不是正确的解决方案。

Second, what would be a way to achieve my goal? 第二,实现目标的方法是什么? A background task ? 后台任务 I've heard of Hangfire . 我听说过Hangfire Is something like Hangfire what I need to use? 我需要使用像Hangfire这样的东西吗? Or could I just use an AJAX call to send the emails? 还是可以仅使用AJAX呼叫发送电子邮件?

Btw, I'm using ASP.NET Core and .NET Framework 4.6.1 顺便说一句,我正在使用ASP.NET Core和.NET Framework 4.6.1

How about using a message queue service (eg RabbitMQ or AWS SQS) running on a separate server? 使用在单独服务器上运行的消息队列服务(例如RabbitMQ或AWS SQS)怎么样? then post a message to that server with details of what needs to be done (in this case what to send to whom), and then the message service can pull messages off the queue at its leisure, process them (send out 1000s of emails) and then get the next thing off the queue. 然后向该服务器发布一条消息,其中包含需要完成的操作的详细信息(在本例中为发送给谁),然后消息服务可以在闲暇时将消息从队列中拉出,进行处理(发送1000封电子邮件)然后从队列中取出下一件事。

I used hangfire in a similar situation. 我在类似情况下使用了Hangfire。 Here's how I implemented it. 这是我的实现方式。

  1. Stored the list of emails to be sent in the database. 将要发送的电子邮件列表存储在数据库中。
  2. Used hangfire to process the emails in the background. 使用hangfire在后台处理电子邮件。

You could use a separate queue/server for the processing. 您可以使用单独的队列/服务器进行处理。 Did the job for me. 为我做了工作。

Check this post on Background Processing in ASP.net using Hangfire 使用Hangfire在ASP.net中的后台处理中查看此帖子

Also, go through the hangfire best practices before implementing. 此外,在实施之前,请仔细阅读hangfire最佳做法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM