用.net創(chuàng)建windows service的總結(jié)(C#代碼)tojike(原作)
2024-07-10 13:01:46
供稿:網(wǎng)友
用.net創(chuàng)建windows service的總結(jié) tojike(原作)
關(guān)鍵字 windows service
前言
net為創(chuàng)建windows service提供了專(zhuān)門(mén)的類(lèi)庫(kù),結(jié)束了以前開(kāi)發(fā)windows service窘迫的局面。你甚至可以不用添加一行代碼,就可以用wizard生成一個(gè)windows service。
一、用wizard生成最基本的框架
此時(shí),系統(tǒng)會(huì)為你生成一個(gè)框架,部分主要源代碼如下:
using system;
using system.collections;
using system.componentmodel;
using system.data;
using system.diagnostics;
using system.serviceprocess;
namespace windowsservice1
{
public class service1 : system.serviceprocess.servicebase
{
private system.componentmodel.container components = null;
public service1()
{
initializecomponent();
}
static void main()
{
system.serviceprocess.servicebase[] servicestorun;
servicestorun = new system.serviceprocess.servicebase[] { new service1() };
system.serviceprocess.servicebase.run(servicestorun);
}
private void initializecomponent()
{
components = new system.componentmodel.container();
this.servicename = "service1";
}
protected override void dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.dispose();
}
}
base.dispose( disposing );
}
protected override void onstart(string[] args)
{
}
protected override void onstop()
{
}
}
}
有必要將其結(jié)構(gòu)講解一下。其中,system.serviceprocess就是關(guān)鍵所在,是引入windows service的地方。其中的onstart()、onstop()兩個(gè)函數(shù)能夠被windows服務(wù)管理器或者mmc調(diào)用,進(jìn)行服務(wù)的啟動(dòng)、停止。
二、構(gòu)建一個(gè)服務(wù)
該框架提供了一個(gè)空的服務(wù),什么也不能做。所以我們要給它添加代碼。比如,我想
做一個(gè)能夠掃描數(shù)據(jù)庫(kù)的服務(wù),要求每次掃描完之后間隔一秒鐘,然后繼續(xù)掃描。
根據(jù)上面的要求,初步設(shè)想需要一個(gè)timer類(lèi),查命名空間,發(fā)現(xiàn)有二個(gè)不同的timer類(lèi),他們是:
1、 system.windows.forms.timer
2、 system.timers.timer
還有一個(gè)system.threading,帶有sleep方法
究竟該用哪個(gè)呢?
細(xì)查msdn,會(huì)找到只有2適合,對(duì)于1來(lái)說(shuō),timer控制時(shí)間不夠精確,對(duì)于線程來(lái)說(shuō),實(shí)現(xiàn)比較困難。
三、規(guī)劃一下流程
基于該服務(wù)的要求,確定服務(wù)的流程如下:
為此,我們定義兩個(gè)函數(shù):_scan(bool _judge)、_do_something()
然后引入system.timers命名空間,并且定義一個(gè)_timer對(duì)象,這些代碼如下:
1、using system.timers; //引入system.timers
2、public system.timers.timer _timer; //定義對(duì)象_timer
3、public bool _scan(bool _judge)
{
//todo
}
4、public void _do_something()
{
//todo
}
然后在initializecomponent()里邊把_timer的elapsed事件添加上,代碼如下:
this._timer.elapsed += new system.timers.elapsedeventhandler(this._timer_elapsed);
定義_timer_elapsed事件,代碼如下:
private void _timer_elapsed(object sender, system.timers.elapsedeventargs e)
{
_timer.interval=1000;
_timer.enabled=false;
if(_scan()==true)
{
_do_something();
}
_timer.enabled=true;
}
最后,我們不要忘記添加windows service的installer,也是一個(gè)wizard,基本上不需要添加一行代碼。然后編譯,生成一個(gè)可執(zhí)行文件。注意:因?yàn)檫@不是普通的可執(zhí)行文件,所以不能通過(guò)雙擊實(shí)現(xiàn)運(yùn)行,只能通過(guò)installutil yourservicename、net start yourservicename、net stop yourservicename、installutil/u yourservicename來(lái)進(jìn)行該服務(wù)的安裝、啟動(dòng)、停止、暫停(可選)、卸載。最好是做成批處理文件,一勞永逸。^_^