我有一个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