2011-03-28 54 views
0

什麼是Windows服務的簡短示例以及如何安裝和運行它?有關Windows服務的C#

我在互聯網上搜索過,但我試過的東西沒有寫入On Start方法的東西。另外,當我試圖安裝它時,錯誤OpenSCManager不斷彈出。

+0

一個Windows服務可以只是一個'dll',事件'OnStart'上的應用程序開始。謹慎向我們展示你想要做什麼? – balexandre 2011-03-28 07:56:06

回答

3
  1. 查找安裝UTIL在C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe

  2. 然後運行InstallUtil.exe "c:\myservice.exe"

  3. 轉到services.msc和然後找到並開始您的服務

+0

我找不到安裝util。有另一種方法來測試應用程序嗎? – elisa 2011-03-28 09:36:45

+0

如果你想調試你的Windows服務,請按照下面的步驟1>添加app.config 2>在你的service.cs中添加這段代碼片段public static void Main(){ #if(!DEBUG) ServiceBase [] ServicesToRun; ServicesToRun = new ServiceBase [] { new MyServiceClassName() }; 運行(ServicesToRun); #else var service = new MyServiceClassName(); service.OnStart(null); System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite); #endif } – 2011-03-28 09:47:21

+0

您使用的是哪個版本的.net?也許從網上下載它 – 2011-03-28 09:53:47

0

我對這個問題的回答給你一步一步的說明,在C#中創建Windows服務。

我回答這個問題說明你需要修改服務,以便它可以安裝和命令行卸載本身。

InstallUtil.exe 1.1以來一直是.NET的一部分,所以它應該是你的系統上。但是,您可能無法使用「正常」命令提示符。如果您安裝了Visual Studio,請打開Visual Studio命令提示符。這將定義適當的環境變量,使InstallUtil無需路徑信息即可訪問。

OnStart()回調使您有機會啓動服務的業務邏輯。如果您在OnStart()回撥中沒有執行任何操作,您的服務將立即關閉。通常情況下,您將開始一個執行您感興趣的工作的線程。下面是一個小例子,向您展示它的外觀。

private static System.Timers.Timer _timer; 

private static void OnTimedEvent(object source, ElapsedEventArgs e) 
{ 
    // Write a message to the event log. 
    string msg = String.Format("The Elapsed event was raised at {0}", e.SignalTime); 
    EventLog.WriteEntry(msg, EventLogEntryType.Information); 
} 

protected override void OnStart(string[] args) 
{ 
    // Create a timer with a 10-econd interval. 
    _timer = new System.Timers.Timer(10000); 

    // Hook up the Elapsed event for the timer. 
    _timer.Elapsed += new ElapsedEventHandler(OnTimedEvent); 

    // Signal the timer to raise Elapsed events every 10 seconds. 
    _timer.Start(); 
} 

protected override void OnStop() 
{ 
    // Stop and dispose of the timer. 
    _timer.Stop(); 
    _timer.Dispose(); 
} 

做這樣的事情會有效地讓你的服務繼續運行,直到它關閉。希望這可以幫助。