天天看點

自定義Window 服務

  自定義window 服務

開發到使用的流程:

1、完成對應的代碼之後(代碼在底下),右鍵MyService.cs 添加安裝程式

2、添加window服務安裝程式

打開Service1.cs【設計】頁面,點選右鍵,選擇【添加安裝程式】,會出現serviceInstaller1和serviceProcessInstaller1兩個元件

将serviceProcessInstaller1的Account屬性設為【LocalSystem】, serviceInstaller1的StartType屬性設為【Automatic】,ServiceName屬性可設定服務名稱,此後在【管理工具】--》【服務】中即顯示此名稱

ProjectInstaller.cs檔案,在安裝服務後一般還需手動啟動(即使上述StartType屬性設為【Automatic】),可在ProjectInstaller.cs添加如下代碼實作安裝後自動啟動

public ProjectInstaller()

{

InitializeComponent();

this.Committed += new InstallEventHandler(ProjectInstaller_Committed);

}

private void ProjectInstaller_Committed(object sender, InstallEventArgs e)

//參數為服務的名字

System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController("服務名稱");

controller.Start();

}

三、安裝、解除安裝window服務

1、輸入cmd(指令行),

4.0:cd C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319

// 2.0:cd C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

2、安裝服務(項目生成的exe檔案路徑)

InstallUtil E:\WindowsService1\bin\Debug\WindowsService1.exe

3、解除安裝服務

InstallUtil /u E:\WindowsService1\bin\Debug\WindowsService1.exe

調試,是在vs 中附加到程序的做法,或者是Debuger

安裝要有完整的bin檔案下Debug的檔案

設定原始服務路口

using System;

using System.Collections.Generic;

using System.Linq;

using System.ServiceProcess;

using System.Text;

using System.Threading.Tasks;

namespace WindowsService

{

static class Program

{

/// <summary>

/// 應用程式的主入口點。

/// </summary>

static void Main()

ServiceBase[] ServicesToRun;

ServicesToRun = new ServiceBase[]

{

new MyService()

};

ServiceBase.Run(ServicesToRun);

}

}

(具體定義的window 服務代碼)

using System.ComponentModel;

using System.Data;

using System.Diagnostics;

using System.Timers;

public partial class MyService : ServiceBase

System.Timers.Timer myTimer;//定時器

public MyService()

int index =0;

protected override void OnStart(string[] args)

myTimer = new System.Timers.Timer();

myTimer.Interval = 3000;//毫秒為機關

myTimer.Elapsed += new System.Timers.ElapsedEventHandler(MyEvent);//這裡要加入我們執行的操作

myTimer.Enabled = true;//允許觸發相關事件,本質是多點傳播委托(對應的委托事件)

//自定義操作

public void MyEvent(object sender, ElapsedEventArgs e)

ProductDemoEntities db = new ProductDemoEntities();

if (index == 0) {

index= db.Products.OrderByDescending(x => x.Id).FirstOrDefault().Id;

}else{

index++;

}

Product product = new Product();

product.Id = index;

product.Name = "空" + index;

product.Category = "自動加入" + index;

product.Price =Convert.ToDecimal( 1.2 + index);

db.Entry<Product>(product).State = EntityState.Added;//entry,set,查詢在修改,異常在修改

//db.Set<Product>(product).Add(product);

// db.Products.Add(product);

db.SaveChanges();

protected override void OnStop()

筆者原創!如果您覺得閱讀本文對您有幫助,請點一下“推薦”按鈕,您的“推薦”将是我最大的寫作動力!歡迎各位轉載,轉載請添加原部落格連接配接,否則保留追究法律責任的權利,謝謝!

YC.Boilerplate 快速開發架構交流,請加群:1060819005

區塊鍊交流請加QQ群:538327407(已滿),群2:135019400.

我的部落格位址:http://www.cnblogs.com/linbin524/