2013年10月17日 星期四

非同步執行緒寄送郵件

非同步執行緒寄送郵件

C#

  1. #region 非同步執行緒寄送郵件
  2.  
  3.  
  4.  
  5.     //1-1.建立非同步委派簽章
  6.  
  7.     delegate string AsyncSendMail();
  8.  
  9.     //1-2.建立了一個具有IAsyncResult參數的Callback方法
  10.  
  11.     void EndCallback(IAsyncResult ar)
  12.  
  13.     {
  14.  
  15.         AsyncSendMail asynDelegate = ar.AsyncState as AsyncSendMail;
  16.  
  17.     }
  18.  
  19.     //1-3.建立執行主體程式
  20.  
  21.     string SendMailAsync()
  22.  
  23.     {
  24.  
  25.         try
  26.  
  27.         {
  28.  
  29.             #region 寄送郵件執行緒-Start
  30.  
  31.             //宣告執行緒
  32.  
  33.             System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
  34.  
  35.             sw.Reset();
  36.  
  37.             //開始執行緒
  38.  
  39.             sw.Start();
  40.  
  41.  
  42.  
  43.             //發送郵件
  44.  
  45.             System.Net.Mail.MailMessage message = new MailMessage();
  46.  
  47.             SmtpClient smtp = new SmtpClient();
  48.  
  49.             message.From = new MailAddress(strFrom);
  50.  
  51.             message.To.Add(new MailAddress(strTo));
  52.  
  53.             message.SubjectEncoding = System.Text.Encoding.UTF8;
  54.  
  55.             message.Subject = "Test";
  56.  
  57.             message.Body = strBody;
  58.  
  59.             smtp.Host = "192.168.1.1";
  60.  
  61.             smtp.Port = "25";
  62.  
  63.             smtp.Send(message);
  64.  
  65.  
  66.  
  67.             //停止執行緒
  68.  
  69.             sw.Stop();
  70.  
  71.  
  72.  
  73.             #endregion  執行緒-End
  74.  
  75.             return "successful";
  76.  
  77.         }
  78.  
  79.         catch (Exception)
  80.  
  81.         {
  82.  
  83.             return "failed";
  84.  
  85.             //throw;
  86.  
  87.         }
  88.  
  89.     }
  90.  
  91.  
  92.  
  93.     protected void Button1_Click(object sender, EventArgs e)
  94.  
  95.     {
  96.  
  97.  
  98.  
  99.         //1-4.實體化委派
  100.  
  101.         AsyncSendMail asynDelegate = new AsyncSendMail(SendMailAsync);
  102.  
  103.         //1-5.開始非同步作業
  104.  
  105.         asynDelegate.BeginInvoke(EndCallback, asynDelegate);
  106.  
  107.  
  108.  
  109.     }
  110.  
  111.  
  112.  
  113. #endregion 非同步執行緒寄送郵件
  114.  

沒有留言:

張貼留言