C#
#region 非同步執行緒寄送郵件
//1-1.建立非同步委派簽章
delegate string AsyncSendMail();
//1-2.建立了一個具有IAsyncResult參數的Callback方法
void EndCallback(IAsyncResult ar)
{
AsyncSendMail asynDelegate = ar.AsyncState as AsyncSendMail;
}
//1-3.建立執行主體程式
string SendMailAsync()
{
try
{
#region 寄送郵件執行緒-Start
//宣告執行緒
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Reset();
//開始執行緒
sw.Start();
//發送郵件
System.Net.Mail.MailMessage message = new MailMessage();
SmtpClient smtp = new SmtpClient();
message.From = new MailAddress(strFrom);
message.To.Add(new MailAddress(strTo));
message.SubjectEncoding = System.Text.Encoding.UTF8;
message.Subject = "Test";
message.Body = strBody;
smtp.Host = "192.168.1.1";
smtp.Port = "25";
smtp.Send(message);
//停止執行緒
sw.Stop();
#endregion 執行緒-End
return "successful";
}
catch (Exception)
{
return "failed";
//throw;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//1-4.實體化委派
AsyncSendMail asynDelegate = new AsyncSendMail(SendMailAsync);
//1-5.開始非同步作業
asynDelegate.BeginInvoke(EndCallback, asynDelegate);
}
#endregion 非同步執行緒寄送郵件
沒有留言:
張貼留言