简体   繁体   English

SendEmailAsync让人怀疑

[英]SendEmailAsync benefits doubtful

I read this on MSDN documentation, which seems to imply that I will still need to wait after calling the SendAsync method in my code, which is pasted below. 我在MSDN文档中看到了这一点, 这似乎意味着我仍然需要在我的代码中调用SendAsync方法之后等待,该方法粘贴在下面。 Is this right? 这是正确的吗? If it is, then I might as well just use the synchronous method of Send rather than SendAsync. 如果是,那么我也可以使用Send而不是SendAsync的同步方法。 My goal was to go to the next email message in my loop and send it without waiting for the previous one to be sent, which would allow me to handle the emailMessages collection more quickly as compared to using Send method. 我的目标是转到循环中的下一封电子邮件并发送它而不等待发送上一封邮件,这样我就可以比使用Send方法更快地处理emailMessages集合。 But it doesn't seem true. 但这似乎不正确。

After calling SendAsync, you must wait for the e-mail transmission to complete before attempting to send another e-mail message using Send or SendAsync. 调用SendAsync后,必须等待电子邮件传输完成后再尝试使用Send或SendAsync发送另一封电子邮件。

I am using C# and .Net framework 4.5. 我正在使用C#和.Net framework 4.5。 In my code, I am trying to send multiple emails from within a loop as in code below using SendAsync method. 在我的代码中,我尝试使用SendAsync方法在循环内发送多封电子邮件,如下面的代码所示。

List<EmailMessage> emailMessages = DAL.GetEmailsToBeSent();
SmtpClient client = new SmtpClient(); 

foreach(EmailMessage emailMessage in emailMessages)
{
  //create a message object from emailMessage object and then send it asynchronously
  client.SendAsync(message);
 //client.Send(message);
}

The advantage of the async method over the non-async alternative is that you don't need to block the current thread. async方法优于非异步替代方法的优点是您不需要阻止当前线程。 This is particularly helpful in UI environments where you don't want to be blocking the UI thread, and also prevents the need for blocking a thread pool thread. 这在您不希望阻止UI线程的UI环境中特别有用,并且还可以防止阻塞线程池线程。

If you're just going to do a blocking wait on the results, it has no advantage over the non-async alternative. 如果您只是对结果进行阻塞等待,那么它与非异步备选方案相比没有任何优势。

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

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