国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

用.NET創建Windows服務

2024-07-10 12:58:42
字體:
來源:轉載
供稿:網友
我們將研究如何創建一個作為windows服務的應用程序。內容包含什么是windows服務,如何創建、安裝和調試它們。會用到system.serviceprocess.servicebase命名空間的類。 

什么是windows服務?

windows服務應用程序是一種需要長期運行的應用程序,它對于服務器環境特別適合。它沒有用戶界面,并且也不會產生任何可視輸出。任何用戶消息都會被寫進windows事件日志。計算機啟動時,服務會自動開始運行。它們不要用戶一定登錄才運行,它們能在包括這個系統內的任何用戶環境下運行。通過服務控制管理器,windows服務是可控的,可以終止、暫停及當需要時啟動。
windows 服務,以前的nt服務,都是被作為windows nt操作系統的一部分引進來的。它們在windows 9x及windows me下沒有。你需要使用nt級別的操作系統來運行windows服務,諸如:windows nt、windows 2000 professional或windows 2000 server。舉例而言,以windows服務形式的產品有:microsoft exchange、sql server,還有別的如設置計算機時鐘的windows time服務。

創建一個windows服務
我們即將創建的這個服務除了演示什么也不做。服務被啟動時會把一個條目信息登記到一個數據庫當中來指明這個服務已經啟動了。在服務運行期間,它會在指定的時間間隔內定期創建一個數據庫項目記錄。服務停止時會創建最后一條數據庫記錄。這個服務會自動向windows應用程序日志當中登記下它成功啟動或停止時的記錄。
visual studio .net能夠使創建一個windows服務變成相當簡單的一件事情。啟動我們的演示服務程序的說明概述如下。
1. 新建一個項目
2. 從一個可用的項目模板列表當中選擇windows服務
3. 設計器會以設計模式打開
4. 從工具箱的組件表當中拖動一個timer對象到這個設計表面上 (注意: 要確保是從組件列表而不是從windows窗體列表當中使用timer) 
5. 設置timer屬性,enabled屬性為false,interval屬性30000毫秒
6. 切換到代碼視圖頁(按f7或在視圖菜單當中選擇代碼),然后為這個服務填加功能

windows服務的構成
在你類后面所包含的代碼里,你會注意到你所創建的windows服務擴充了system.serviceprocess.service類。所有以.net方式建立的windows服務必須擴充這個類。它會要求你的服務重載下面的方法,visual studio默認時包括了這些方法。
• dispose – 清除任何受控和不受控資源(managed and unmanaged resources)
• onstart – 控制服務啟動
• onstop – 控制服務停止
數據庫表腳本樣例
在這個例子中使用的數據庫表是使用下面的t-sql腳本創建的。我選擇sql server數據庫。你可以很容易修改這個例子讓它在access或任何你所選擇的別的數據庫下運行。
create table [dbo].[myservicelog] (
   [in_logid] [int] identity (1, 1) not null,
   [vc_status] [nvarchar] (40) 
           collate sql_latin1_general_cp1_ci_as not null,
   [dt_created] [datetime] not null
) on [primary]

windows服務樣例
下面就是我命名為myservice的windows服務的所有源代碼。大多數源代碼是由visual studio自動生成的。
using system;
using system.collections;
using system.componentmodel;
using system.data;
using system.data.sqlclient;
using system.diagnostics;
using system.serviceprocess;
namespace codeguru.mywindowsservice
{
  public class myservice : system.serviceprocess.servicebase
  {
   private system.timers.timer timer1;
   /// <remarks> 
   /// required designer variable.
   /// </remarks>
   private system.componentmodel.container components = null;
   public myservice()
   {
       // this call is required by the windows.forms 
       // component designer.
     initializecomponent();
   }
   // the main entry point for the process
   static void main()
   {
     system.serviceprocess.servicebase[] servicestorun;
   
     servicestorun = new system.serviceprocess.servicebase[] 
{ new myservice() };
     system.serviceprocess.servicebase.run(servicestorun);
   }
   /// <summary> 
   /// required method for designer support - do not modify 
   /// the contents of this method with the code editor.
   /// </summary>
   private void initializecomponent()
   {
     this.timer1 = new system.timers.timer();
     ((system.componentmodel.isupportinitialize)
(this.timer1)).begininit();
     // 
     // timer1
     // 
     this.timer1.interval = 30000;
     this.timer1.elapsed += 
   new system.timers.elapsedeventhandler(this.timer1_elapsed);
     // 
     // myservice
     // 
     this.servicename = "my sample service";
     ((system.componentmodel.isupportinitialize)
(this.timer1)).endinit();
   }
   /// <summary>
   /// clean up any resources being used.
   /// </summary>
   protected override void dispose( bool disposing )
   {
     if( disposing )
     {
      if (components != null) 
      {
         components.dispose();
      }
     }
     base.dispose( disposing );
   }
   /// <summary>
   /// set things in motion so your service can do its work.
   /// </summary>
   protected override void onstart(string[] args)
   {
     this.timer1.enabled = true;
     this.logmessage("service started");
   }
 
   /// <summary>
   /// stop this service.
   /// </summary>
   protected override void onstop()
   {
     this.timer1.enabled = false;
     this.logmessage("service stopped");
   }
   /*
    * respond to the elapsed event of the timer control
    */
   private void timer1_elapsed(object sender, 
system.timers.elapsedeventargs e)
   {
     this.logmessage("service running");
   }
   /*
    * log specified message to database
    */
   private void logmessage(string message)
   {
     sqlconnection connection = null;
     sqlcommand command = null;
     try
     {
      connection = new sqlconnection( 
"server=localhost;database=sampledatabase;integrated 
security=false;user id=sa;password=;");
command = new sqlcommand(
"insert into myservicelog (vc_status, dt_created) 
values (’" + message + "’,getdate())", connection);
      connection.open();
      int numrows = command.executenonquery();
     }
     catch( exception ex )
     {
      system.diagnostics.debug.writeline(ex.message);
     }
     finally
     {
      command.dispose();
      connection.dispose();
     }
   }
  }
}

安裝windows服務
windows服務不同于普通windows應用程序。不可能簡簡單單地通過運行一個exe就啟動windows服務了。安裝一個windows服務應該通過使用.net framework提供的installutil.exe來完成,或者通過諸如一個microsoft installer (msi)這樣的文件部署項目完成。

添加服務安裝程序
創建一個windows服務,僅用installutil程序去安裝這個服務是不夠的。你必須還要把一個服務安裝程序添加到你的windows服務當中,這樣便于installutil或是任何別的安裝程序知道應用你服務的是怎樣的配置設置。
1. 將這個服務程序切換到設計視圖
2. 右擊設計視圖選擇“添加安裝程序”
3. 切換到剛被添加的projectinstaller的設計視圖
4. 設置serviceinstaller1組件的屬性: 
    1) servicename = my sample service
    2) starttype = automatic
5. 設置serviceprocessinstaller1組件的屬性 
    1) account = localsystem
6. 生成解決方案
在完成上面的幾個步驟之后,會自動由visual studio產生下面的源代碼,它包含于projectinstaller.cs這個源文件內。
using system;
using system.collections;
using system.componentmodel;
using system.configuration.install;
namespace codeguru.mywindowsservice
{
  /// <summary>
  /// summary description for projectinstaller.
  /// </summary>
  [runinstaller(true)]
  public class projectinstaller : 
system.configuration.install.installer
  {
   private system.serviceprocess.serviceprocessinstaller 
serviceprocessinstaller1;
   private system.serviceprocess.serviceinstaller serviceinstaller1;
   /// <summary>
   /// required designer variable.
   /// </summary>
   private system.componentmodel.container components = null;
   public projectinstaller()
   {
     // this call is required by the designer.
     initializecomponent();
     // todo: add any initialization after the initcomponent call
   }
   #region component designer generated code
   /// <summary>
   /// required method for designer support - do not modify
   /// the contents of this method with the code editor.
   /// </summary>
   private void initializecomponent()
   {
     this.serviceprocessinstaller1 = new 
system.serviceprocess.serviceprocessinstaller();
     this.serviceinstaller1 = new 
system.serviceprocess.serviceinstaller();
     // 
     // serviceprocessinstaller1
     // 
     this.serviceprocessinstaller1.account = 
system.serviceprocess.serviceaccount.localsystem;
     this.serviceprocessinstaller1.password = null;
     this.serviceprocessinstaller1.username = null;
     // 
     // serviceinstaller1
     // 
     this.serviceinstaller1.servicename = "my sample service";
     this.serviceinstaller1.starttype = 
system.serviceprocess.servicestartmode.automatic;
     // 
     // projectinstaller
     // 
     this.installers.addrange(new 
system.configuration.install.installer[] 
{this.serviceprocessinstaller1, this.serviceinstaller1});
}
   #endregion
  }
}

用installutil安裝windows服務
現在這個服務已經生成,你需要把它安裝好才能使用。下面操作會指導你安裝你的新服務。
1. 打開visual studio .net命令提示
2. 改變路徑到你項目所在的bin/debug文件夾位置(如果你以release模式編譯則在bin/release文件夾)
3. 執行命令“installutil.exe mywindowsservice.exe”注冊這個服務,使它建立一個合適的注冊項。
4. 右擊桌面上“我的電腦”,選擇“管理”就可以打計算機管理控制臺
5. 在“服務和應用程序”里面的“服務”部分里,你可以發現你的windows服務已經包含在服務列表當中了
6. 右擊你的服務選擇啟動就可以啟動你的服務了
在每次需要修改windows服務時,這就會要求你卸載和重新安裝這個服務。不過要注意在卸載這個服務前,最好確保服務管理控制臺已經關閉,這會是一個很好的習慣。如果沒有這樣操作的話,你可能在卸載和重安裝windows服務時會遇到麻煩。僅卸載服務的話,可以執行相的installutil命令用于注銷服務,不過要在后面加一個/u命令開關。

調試windows服務
從另外的角度度看,調試windows服務絕不同于一個普通的應用程序。調試windows服務要求的步驟更多。服務不能象你對普通應用程序做的那樣,只要簡單地在開發環境下執行就可以調試了。服務必須首先被安裝和啟動,這一點在前面部分我們已經做到了。為了便于跟蹤調試代碼,一旦服務被啟動,你就要用visual studio把運行的進程附加進來(attach)。記住,對你的windows服務做的任何修改都要對這個服務進行卸載和重安裝。

附加正在運行的windows服務
為了調試程序,有些附加windows服務的操作說明。這些操作假定你已經安裝了這個windows服務并且它正在運行。
1. 用visual studio裝載這個項目 
2. 點擊“調試”菜單
3. 點擊“進程”菜單
4. 確保 顯示系統進程 被選
5. 在 可用進程 列表中,把進程定位于你的可執行文件名稱上點擊選中它
6. 點擊 附加 按鈕
7. 點擊 確定
8. 點擊 關閉
9. 在timer1_elapsed方法里設置一個斷點,然后等它執行

總結
現在你應該對windows服務是什么,以及如何創建、安裝和調試它們有一個粗略的認識了。windows服務的額處的功能你可以自行研究。這些功能包括暫停(onpause)和恢復(oncontinue)的能力。暫停和恢復的能力在默認情況下沒有被啟用,要通過windows服務屬性來設置。

收集最實用的網頁特效代碼!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 永和县| 石城县| 漳平市| 肇东市| 淄博市| 金川县| 万州区| 荣昌县| 修水县| 景东| 呈贡县| 朔州市| 临湘市| 金乡县| 鄂托克旗| 浠水县| 吉水县| 四平市| 栾城县| 衡水市| 江达县| 苏尼特右旗| 嵩明县| 太谷县| 白水县| 富锦市| 清远市| 东方市| 昌图县| 环江| 会昌县| 仪陇县| 河北区| 永吉县| 曲靖市| 石首市| 平陆县| 馆陶县| 收藏| 耒阳市| 察哈|