2017-02-22 70 views
0

SmtpClient班,SendAsyncCancel取消SendMailAsync方法嗎?SendAsyncCancel取消SendMailAsync嗎?

我在www上看到一些暗示它的代碼示例。

然而MSDN says

使用SendAsyncCancel方法取消未決SendAsync操作。如果有郵件等待發送,則此方法釋放用於存儲郵件的資源。如果沒有等待發送的郵件,這個方法什麼也不做。

...這意味着它取消SendAsync而不是SendMailAsync

有沒有辦法取消SendMailAsync?如果不是,爲什麼不呢?

如果你想取消異步發送(因此使用舊SendAsync,而不是較新的SendMailAsync),有什麼用SendAsync代替SendMailAsync的任何其他缺點?

回答

0

我試圖從ASP網頁的背部後處理程序調用SendMailAsync,它拋出一個異常:

System.InvalidOperationException: Asynchronous operations are not allowed in this context. Page starting an asynchronous operation has to have the Async attribute set to true and an asynchronous operation can only be started on a page prior to PreRenderComplete event. 
    at System.Web.LegacyAspNetSynchronizationContext.OperationStarted() 
    at System.ComponentModel.AsyncOperation.CreateOperation(Object userSuppliedState, SynchronizationContext syncContext) 
    at System.Net.Mail.SmtpClient.SendAsync(MailMessage message, Object userToken) 
    --- End of inner exception stack trace --- 
    at System.Net.Mail.SmtpClient.SendAsync(MailMessage message, Object userToken) 
    at System.Net.Mail.SmtpClient.SendMailAsync(MailMessage message) 
    at MyWebSite.AdminTest.TestEmail.<sendAsynchronous>d__9.MoveNext() 

由此我推斷兩件事情:

  1. SendMailAsync的確使用SendAsync實現(您可以在異常的調用堆棧中看到它)。因此,SendAsyncCancel可能也適用於SendMailAsync。
  2. 除非您想處理「在此上下文中不允許異步操作」問題,否則無法從ASP調用SendMailAsync。這是discussed here,看起來可能是混亂。而我認爲調用SendAsync可能沒有這個問題(因爲我在其他地方使用HttpClient.SendAsyncContinueWith,最後CountdownEvent.Wait等待操作完成,而沒有看到拋出此異常。

當通過HostingEnvironment.QueueBackgroundWorkItem調用SendMailAsync時,可以使用SendMailAsync。