日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
C#實現(xiàn)Windows后臺服務(wù)實例淺析

C#實現(xiàn)Windows后臺服務(wù)實例之前要明白的一些概念:所謂Windows后臺服務(wù),即后臺自動運行的程序,一般隨操作系統(tǒng)啟動而啟動,在我的電腦 服務(wù)后應(yīng)用程序 服務(wù)里面能看到當前電腦的服務(wù).一般而言,程序上用VC、C++寫Windows服務(wù),但是我對這些語言不是很熟,一般編程用C#較多,所以就用C#語言寫了一個Windows服務(wù).

創(chuàng)新互聯(lián)主要從事網(wǎng)站制作、成都做網(wǎng)站、網(wǎng)頁設(shè)計、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)陽泉,十多年網(wǎng)站建設(shè)經(jīng)驗,價格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):13518219792

C#實現(xiàn)Windows后臺服務(wù)實例其實需求是這樣的,做那個報價系統(tǒng)的時候加入了發(fā)短信的功能,訂單處理完即將發(fā)貨的時候要發(fā)送短信都客戶手機上,公司內(nèi)部員工處理訂單超時要自動發(fā)短信,群發(fā)產(chǎn)品促銷信息到客戶手機上等,還有定時發(fā)送短信的需求,所以***面決定把發(fā)短信的模塊獨立出來,以后還有什么功能方便一起調(diào)用,而最終選擇了采用Windows后臺服務(wù).

C#實現(xiàn)Windows后臺服務(wù)實例其實Windows服務(wù)并不好做到通用,它并不能在用戶的界面顯示一些什么信息等,它只是在后臺默默的處理一些事情,起著輔助的作用.那如何實現(xiàn)發(fā)送段信通用調(diào)用的接口呢?它們之間的信息又是如何來交互呢?數(shù)據(jù)庫!對,就是它存儲數(shù)據(jù)信息的.而數(shù)據(jù)庫都能很方便的訪問操作.把發(fā)送短信的后臺服務(wù)定時去訪問一個數(shù)據(jù)庫,而另外任何要發(fā)送短信的地方也訪問數(shù)據(jù)庫,并插入一條要發(fā)送的短信到表里面,稍后Windows后臺服務(wù)訪問該表將此短信發(fā)送出去.這可能是一個比較蠢的方法,但實現(xiàn)起來較簡單.

C#實現(xiàn)Windows后臺服務(wù)實例首先,由于它是要安裝的,所以它運行的時候就需要一個安裝類Installer將服務(wù)安裝到計算機,新建一個后臺服務(wù)安裝類繼承自Installer,安裝初始化的時候是以容器進行安裝的,所以還要建立ServiceProcessInstaller和ServiceInstaller服務(wù)信息組件添加到容器安裝,在Installer類增加如下代碼:

 
 
 
 
  1. private System.ComponentModel.IContainer components = null;  
  2. private System.ServiceProcess.ServiceProcessInstaller spInstaller;  
  3. private System.ServiceProcess.ServiceInstaller sInstaller;  
  4. private void InitializeComponent()  
  5. {  
  6. components = new System.ComponentModel.Container();  
  7.  
  8. // 創(chuàng)建ServiceProcessInstaller對象和ServiceInstaller對象  
  9. this.spInstaller = new System.ServiceProcess.
  10. ServiceProcessInstaller();  
  11. this.sInstaller = new System.ServiceProcess.ServiceInstaller();  
  12.  
  13. // 設(shè)定ServiceProcessInstaller對象的帳號、用戶名和密碼等信息  
  14. this.spInstaller.Account = System.ServiceProcess.
  15. ServiceAccount.LocalSystem;  
  16. this.spInstaller.Username = null;  
  17. this.spInstaller.Password = null;  
  18.  
  19. // 設(shè)定服務(wù)名稱  
  20. this.sInstaller.ServiceName = "SendMessage";  
  21. sInstaller.DisplayName = "發(fā)送短信服務(wù)";  
  22. sInstaller.Description = "一個定時發(fā)送短信的服務(wù)";  
  23.  
  24. // 設(shè)定服務(wù)的啟動方式  
  25. this.sInstaller.StartType = System.ServiceProcess.
  26. ServiceStartMode.Automatic;  
  27.  
  28. this.Installers.AddRange(new System.Configuration.
  29. Install.Installer[] { this.spInstaller, this.sInstaller });  

C#實現(xiàn)Windows后臺服務(wù)實例再添加一個服務(wù)類繼承自ServiceBase,我們可以重寫基類的OnStart、OnPause、OnStop、OnContinue等方法來實現(xiàn)我們需要的功能并設(shè)置指定一些屬性.由于是定事發(fā)送短信的服務(wù),自然少不了Windows記時器,在OnStart事件里我們寫入服務(wù)日志,并初始化記時器.

 
 
 
 
  1. private System.Timers.Timer time;  
  2. private static readonly string CurrentPath = 
  3. Application.StartupPath + "\\";  
  4. protected override void OnStart(string[] args)  
  5. {  
  6. string path = CurrentPath + "Log\\start-stop.log";  
  7. FileStream fs = new FileStream(path, FileMode.
  8. Append, FileAccess.Write);  
  9. StreamWriter sw = new StreamWriter(fs);  
  10. sw.WriteLine("The Service is Starting On " + 
  11. DateTime.Now.ToString());  
  12. sw.Flush();  
  13. sw.Close();  
  14. fs.Close();  
  15.  
  16. time = new System.Timers.Timer(1000 * Convert.
  17. ToInt32(GetSettings("TimeSpan")));  
  18. time.Enabled = true;  
  19. time.Elapsed += this.TimeOut;  
  20. time.Start();  

C#實現(xiàn)Windows后臺服務(wù)實例實例化記時器類啟動后,將在指定時間間隔觸發(fā)Elapsed指定事件,如上GetSettings為讀取我App.config文件里一個配置節(jié)點(值為30)的方法,所以上面將會每隔30秒調(diào)用TimeOut方法.而改方法就是我們發(fā)短信的具體操作.代碼如下:

 
 
 
 
  1. private void TimeOut(object sender, EventArgs e)  
  2. {  
  3. try 
  4. {  
  5. if (GetSettings("Enabled").ToLower() == "true")  
  6. {  
  7. SqlConnection con = new SqlConnection(GetSettings("ConnString"));  
  8. SqlCommand cmd = new SqlCommand("select [sysid],
  9. [admin_inner_code],[user_inner_code],[phone],
  10. [message],[sendtime] from [tbl_note_outbox]", con);  
  11. con.Open();  
  12. SqlDataReader rdr = cmd.ExecuteReader();  
  13. while (rdr.Read())  
  14. {  
  15. string phone = rdr["phone"].ToString();  
  16. string message = rdr["message"].ToString();  
  17. string sendtime = rdr["sendtime"].ToString();  
  18. System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("GB2312");  
  19. string url = string.Format("http://211.155.23.205/
  20. isapi.dll?SendSms&AgentID={0}&PassWord={1}&phone={2}&msg={3}&sendtime={4}", 
  21. GetSettings("AgentID"), GetSettings("PassWord"), 
  22. phone,System.Web.HttpUtility.UrlEncode( message,encoder), sendtime);  
  23. System.Net.WebClient wClient = new System.Net.WebClient();  
  24. string msg = System.Text.Encoding.Default.GetString(wClient.DownloadData(url));  
  25. wClient.Dispose();  
  26.  
  27. //刪除已經(jīng)發(fā)送成功的,并保存發(fā)送記錄  
  28. if (msg == "發(fā)送成功")  
  29. {  
  30. DateTime dtsend = sendtime == "0" ? DateTime.Now : 
  31. DateTime.ParseExact(sendtime, "yyyyMMddHHmmss", null);  
  32. string sql = string.Format("delete from 
  33. [tbl_note_outbox] where [sysid]={0} INSERT INTO [tbl_note_log] 
  34. ([admin_inner_code],[user_inner_code],[status],[phone],
  35. [message],[sendtime]) VALUES('{1}','{2}','{3}','{4}','{5}','{6}')",
  36.  rdr["sysid"], rdr["admin_inner_code"], rdr["user_inner_code"],
  37.  msg, phone, message, dtsend);  
  38. SqlConnection conn = new SqlConnection(GetSettings("ConnString"));  
  39. SqlCommand delete = new SqlCommand(sql, conn);  
  40. conn.Open();  
  41. delete.ExecuteNonQuery();  
  42. conn.Close();  
  43. delete.Dispose();  
  44. }  
  45.  
  46. }  
  47. rdr.Close();  
  48. con.Close();  
  49. cmd.Dispose();  
  50. }  
  51. }  
  52. catch (Exception ex)  
  53. {  
  54. string errorPath = CurrentPath + "Log\\error.log";  
  55. if (!File.Exists(errorPath))  
  56. {  
  57. FileStream create = File.Create(errorPath);  
  58. create.Close();  
  59. }  
  60. FileStream fs = new FileStream(errorPath, 
  61. FileMode.Append, FileAccess.Write);  
  62. StreamWriter sw = new StreamWriter(fs);  
  63. sw.WriteLine("Exception: " +ex.Message+" --"+
  64.  DateTime.Now.ToString());  
  65. sw.Flush();  
  66. sw.Close();  
  67. fs.Close();  
  68. }  
  69.  

C#實現(xiàn)Windows后臺服務(wù)實例上面我們使用try、catch訪問數(shù)據(jù)庫,并記錄錯誤異常信息. 發(fā)送短信是使用發(fā)送一個Web請求發(fā)送出去的,要注意請求url字符串的編碼類型,要與請求頁面編碼一致,不然會出現(xiàn)亂碼.上面我們請求的是智網(wǎng)通集團短信(網(wǎng)址:http://www.09168.net/)的Web接口,通過訪問他的網(wǎng)站來實現(xiàn)發(fā)短信,當然還要傳遞一些用戶名、密碼、手機號碼和要發(fā)送的短信息等參數(shù).他的收費平均大概為7分/條的樣子,其實我原本不想用發(fā)送Web請求的這樣方式來發(fā)送短信的,它本身提供了調(diào)用它發(fā)送短信的DLL,而且還有vc、delphi調(diào)用的Demo,但是沒有用C#調(diào)用的例子,我剛開始試著用非托管動態(tài)鏈接庫他提供的DLL,不知方法調(diào)用那里出錯了一直都沒能成功發(fā)送出短信,所以后來就用了他的Web方式接口了.他頁面直接返回發(fā)送短信的狀態(tài)信息.返回發(fā)送成功則短信發(fā)送成功,成功后我再將此條信息從要發(fā)送短信表里刪除并保存在發(fā)送記錄表里面,以備日后方便查詢.其實登陸他的官網(wǎng)進入后臺也能方便的查詢,如下圖.

C#實現(xiàn)Windows后臺服務(wù)實例發(fā)送短信服務(wù)的代碼基本上搞定了,就看怎么在服務(wù)器上安裝部署了.C#寫的Windows后臺服務(wù)不能直接安裝,需要借助.NET Framework里面的InstallUtil.exe安裝工具安裝,我們可以做成一個執(zhí)行CMD命令的文件BAT文件來安裝啟動它,命令如下:

 
 
 
 
  1. %windir%\Microsoft.NET\  
  2. Framework\v2.0.50727\  
  3. InstallUtil.exe %CD%\  
  4. SendMessage.exe  
  5. net start SendMessage 

安裝完成以后,我們可以在我的電腦管理服務(wù)里面看到才安裝上的后臺服務(wù).

經(jīng)測試,采用定時訪問數(shù)據(jù)庫發(fā)送短信的服務(wù)并不是很耗資源,剛啟動的時候只占用內(nèi)存為7、8M左右,經(jīng)過在服務(wù)器上連續(xù)運行幾天不關(guān)閉占用的內(nèi)存也只升到15M左右,運行比較穩(wěn)定,這里提供一個短信二次開發(fā)接口說明,有興趣的朋友可以去下載看下.

智網(wǎng)動力集團短信二次開發(fā)說明文檔示例

特別申明:本文及內(nèi)容如非特別注明,均為本人Jonllen原創(chuàng),版權(quán)均歸原作者個人所有,轉(zhuǎn)載必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權(quán)利。

C#實現(xiàn)Windows后臺服務(wù)實例的基本情況就向你介紹到這里,希望對你了解和學習C#實現(xiàn)Windows后臺服務(wù)實例有所幫助。

【編輯推薦】

  1. C#windows服務(wù)狀態(tài)改變操作淺析
  2. C#Windows服務(wù)程序開發(fā)實例介紹
  3. C#啟動Windows服務(wù)及關(guān)閉實例實現(xiàn)
  4. C#啟動Windows服務(wù)的窗體程序淺析
  5. C#Windows服務(wù)程序之安裝項目

當前標題:C#實現(xiàn)Windows后臺服務(wù)實例淺析
當前網(wǎng)址:http://www.5511xx.com/article/cdecccd.html