2016-05-09 35 views
0

使用C#/ Asp.Net如何在重定向之前完成請求

我有一個應用程序發送到Web服務。返回時有一對夫婦的事情發生:

void Cleanup(Response response) 
    { 
      // My web service takes up to 30 seconds 
      // then this method is called 

      // I send this email 
      var email = SaleEmail.Create(
      response.ID 
      DateTime.Now, 
      "A sale was made!"); 

     email.Send(); 

     // Then redirect 
     Response.Redirect(response.RedirectUrl, false); 
     Context.ApplicationInstance.CompleteRequest(); 
    } 

的想法是,在網絡服務的郵件發送完畢,那麼頁面重定向。

此前,我使用了正常的重定向 - 結果是90%的電子郵件從未發送過。

我改變了重定向模式,但它仍然不完美 - 我猜25%的電子郵件仍然沒有通過。

任何人都建議我對模式有任何改進?

電子郵件代碼:

 public static void Send(MailMessage message) 
     { 
      Guard.Argument.NotNull(() => message); 

      var c = new SmtpClient(); 

      try 
      { 
       c.Send(message); 
      } 
      catch (Exception ex) 
      { 
      } 
      finally 
      { 
       c.Dispose(); 
       message.Dispose(); 
      } 
     } 
+0

你使用smtpClient? –

+0

我使用WebClient,但這不是問題 - 如果我刪除重定向一切工作正常。我曾經顯示一個啓動畫面,讓用戶重定向自己,但不再可能。 –

+0

我在說使用smtpClient發送郵件? –

回答

2

也許
嘗試實施異步任務方法sendAsync並等待 這AWAIT將幫助您等待需要多少跳之前發送電子郵件至重定向

//async Task 
public async Task Cleanup(Response response) 
{ 
    using (var smtpClient = new SmtpClient()) 
    { 
     await smtpClient.SendAsync();...//await 
    } 
} 
+0

感謝您的答覆 - 不幸的是,該網站目前正在運行ASP。淨4,所以我不能使用異步 –

+0

http://stackoverflow.com/questions/13266277/how-do-i-call-async-methods-in-asp-net-c-sharp-4-0 –

+0

看這裏你仍然能夠以不同的方式達到目標 –

1

你應該改寫你的初始化,使它看起來像這樣:

smtpClient.SendAsync(); 
smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted); 

smtpClient_SendCompleted功能編寫代碼重定向

相關問題