托管到服务器时,任务或线程无法正常工作/运行

时间:2021-12-21 16:51:29

So I am trying to send email as notification to user and I want it to run asynchronously. Initially I implemented with Task.Factory.StartNew as below:

所以我试图将电子邮件作为通知发送给用户,我希望它以异步方式运行。最初我使用Task.Factory.StartNew实现如下:

Task.Factory.StartNew(() => { _notify.NotifyUser(params); });

NotifyUser is a void method which actually sends email to the user.

NotifyUser是一种实际向用户发送电子邮件的void方法。

But it was never executing the method. I have placed a log message inside NotifyUser method, which was never getting logged.

但它从未执行过该方法。我在NotifyUser方法中放置了一条日志消息,该方法从未被记录。

I followed this post and came to know that

我按照这篇文章来了解这一点

Sometimes this kind of behaviour is an indication of an overloaded ThreadPool. Seeing as these are long running/blocking tasks, they should not be scheduled to run in the ThreadPool, which is where Task.Factory.StartNew will be sending them using the default TaskScheduler

有时这种行为表明ThreadPool过载。看到这些是长时间运行/阻塞任务,它们不应该被安排在ThreadPool中运行,这是Task.Factory.StartNew将使用默认的TaskScheduler发送它们的地方

and so I followed what was suggested there which is as below:

所以我按照那里的建议进行了如下操作:

ThreadStart action=()=>{
    _notify.NotifyUser(params);
};
Thread thread=new Thread(action){IsBackground=true};
thread.Start();

Found no luck with the above approach too. Again I followed one more approach which even did not work.

上述方法也没有运气。我再次采用了一种甚至不起作用的方法。

Task task = new Task(() => {
     _notify.NotifyUser(params); 
});
task.RunSynchronously(); //or task.Start();

Is there any other way I can run this task of sending email? I've heard about async await but I read that it will not be used on void methods. Can someone let me know what would be the best approach here?

有没有其他方法可以运行这个发送电子邮件的任务?我听说异步等待,但我读到它不会用于void方法。有人能告诉我这里最好的方法是什么吗?


Update

ThreadPool.QueueUserWorkItem(t =>
{
   _notify.NotifyUser(params); 
});

so that it will execute this method when the thread is available. But still no luck here.

这样当线程可用时它将执行此方法。但这里仍然没有运气。

Actual Code

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddEditUser(UVModel model)
{
    if (HasPermission())
    {
         string message = string.Empty;
         bool success = false;
         string returnUrl = string.Empty;
         if (ModelState.IsValid)
         {
             using (_db = new EFDB())
             {
                   //fill user model
                   _db.Entry(user).State = state;
                   _db.SaveChanges();
                   _notify = new SendNotification();
                   _notify.NotifyUser(params); //This has to be asynchronous
                   success = true;
                   returnUrl = Url.Action("Action", "Controller", null, HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Host);
                   message="success";
             }
          }
          else
                message = "Server side validation failed!";
          return Json(new { result = success, message = message, redirectUrl = returnUrl }, JsonRequestBehavior.AllowGet);
    }
    else
          return Json(new { result = false, message = "You do not have permission to perform this action!", redirectUrl = "" }, JsonRequestBehavior.AllowGet);
}

SendNotification.cs

public void NotifyUser(Parameter params)
{
    using (MailMessage mail = new MailMessage())
    {
            _db = new EFDB();
            mail.To.Add(params.toAddress);
            mail.From = params.from;

            mail.Subject = params.subject;
            mail.Body = params.body;
            mail.IsBodyHtml = true;
            mail.Priority = MailPriority.High;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "some smtp host";
            smtp.Port = 25;
            smtp.UseDefaultCredentials = false;
            smtp.EnableSsl = false;
            smtp.Credentials = new NetworkCredential("uname", "pwd");
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            try
            {
                smtp.Send(mail);
            }
            catch (SmtpFailedRecipientException se)
            {
                LogError.LogMessage("SmtpFailedRecipientException Exception - " + se.Message.ToString(), context);
            }
            catch (SmtpException se)
            {
                LogError.LogMessage("SmtpException - " + se.Message.ToString(), context);
            }
    }
}

1 个解决方案

#1


1  

You should never use StartNew unless you're doing dynamic task-based parallelism. I explain why on my blog in excruciating detail.

除非您正在进行基于动态任务的并行操作,否则不应使用StartNew。我在博客上解释为什么会有一些令人难以忍受的细节。

Assuming that you're running on ASP.NET, you should use HostingEnvironment.QueueBackgroundWorkItem. I suspect that you're seeing an exception from your delegate, and QBWI will log any exceptions to the event log.

假设您在ASP.NET上运行,则应使用HostingEnvironment.QueueBackgroundWorkItem。我怀疑你看到了你的委托的异常,QBWI会记录事件日志的任何异常。

#1


1  

You should never use StartNew unless you're doing dynamic task-based parallelism. I explain why on my blog in excruciating detail.

除非您正在进行基于动态任务的并行操作,否则不应使用StartNew。我在博客上解释为什么会有一些令人难以忍受的细节。

Assuming that you're running on ASP.NET, you should use HostingEnvironment.QueueBackgroundWorkItem. I suspect that you're seeing an exception from your delegate, and QBWI will log any exceptions to the event log.

假设您在ASP.NET上运行,则应使用HostingEnvironment.QueueBackgroundWorkItem。我怀疑你看到了你的委托的异常,QBWI会记录事件日志的任何异常。