我有一個Web服務來發送電子郵件在C#C# - SMTP異步 - 回調的Web服務客戶端
[WebMethod]
public string sendEmail()
{
MailMessage mail = new MailMessage();
SmtpClient smtpsvr = new SmtpClient("smtp.gmail.com");
// mail settings
// smtpsvr settings
smtpsvr.SendCompleted += new SendCompletedEventHandler(sentCompleteCallBack);
try
{
smtpsvr.SendAsync(mail, "Email 1");
return "sent"; //this return only indicate email has been sent out
}
catch (Exception)
{
return "failed";
}
}
private void sentCompleteCallBack(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null) //error
{
sendResult = "email failed " + (string)e.UserState;
}
else
{ //this result, indicate the process of sending email has been completed
sendResult = "email sent " + (string)e.UserState;
}
// ??? haw to pass sendResult value to client page
}
我嘗試使用性能串,串級拿到sendResult值;但最後在客戶端頁面(aspx)中,只有空/空。我只能得到string sendEmail()的值。
如何將sendResult值傳遞迴客戶端? 非常感謝您的幫助!
/* ** * ** * ** */ 編輯
可能是我必須要改變這樣的代碼? (仍在使用sendAsync()
[WebMethod]
public string sendEmail()
{
MailMessage mail = new MailMessage();
SmtpClient smtpsvr = new SmtpClient("smtp.gmail.com");
//mail settings
//smtpsvr settings
smtpsvr.SendCompleted += new SendCompletedEventHandler(sentCompleteCallBack);
try
{
smtpsvr.SendAsync(mail, "email 1");
return "sent";
}
catch (Exception)
{
return "failed";
}
}
private void sentCompleteCallBack(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null) //error
{
//write to DB_email_status = "failed"
}
else
{
//write to DB_email_status = "success"
}
}
在客戶端頁面(ASPX): (1)調用Web服務來發送電子郵件 (2)得到sendEmail()方法電子郵件發送的字符串值 (3。 )button_onclick:從DB_email_status視圖/獲取數據 (???)是這種情況下achieveable (!!!)非常感謝
感謝Anthony的回覆。所以我想,我必須使用send()重新設計代碼,但需要等待進程,或使用sendAsync(),但將結果寫入數據庫(?)。請看我的下一篇文章。謝謝 – user1561727 2012-07-30 03:55:40
oopsss..sorry,我的意思是,請參閱我編輯的問題,再次感謝。 – user1561727 2012-07-30 04:15:18
是的,這將工作。還有另一種出路。
而不是從webservice創建異步調用,您可以從客戶端創建一個異步調用,它將等待,直到它獲得最終響應(。從webserive發送())。一個原始的僞代碼看起來像這樣
客戶端:{1)啓動異步線程並映射到另一個函數2)調用服務器}服務器:{1)使用.send()發送郵件並將結果傳回給等待客戶端}。這有助於? – 2012-07-30 04:29:04