您的位置:首页 > 其它

创建Windows服务(Windows Services)N种方式总结

2015-07-21 10:04 513 查看
最近由于工作需要,写了一些windows服务程序,有一些经验,我现在总结写出来。

目前我知道的创建创建Windows服务有3种方式:

a.利用.net框架类ServiceBase

b.利用组件Topshelf

c.利用小工具instsrv和srvany

下面我利用这3种方式,分别做一个windows服务程序,程序功能就是每隔5秒往程序目录下记录日志:

a.利用.net框架类ServiceBase

本方式特点:简单,兼容性好

通过继承.net框架类ServiceBase实现

第1步: 新建一个Windows服务

view
sourceprint?

01.
public
partial
class
Service1
: ServiceBase


02.
{


03.
readonly
Timer
_timer;


04.


05.
private
static
readonly
string
FileName
= Path.GetDirectoryName (Assembly.GetExecutingAssembly ().Location ) + @
"\"
+ "
test.txt";


06.


07.
public
Service1
()


08.
{


09.
InitializeComponent
();


10.


11.
_timer
=
new
Timer
(5000 )


12.
{


13.
AutoReset
=
true
,


14.
Enabled
=
true


15.
};


16.


17.
_timer.Elapsed
+=
delegate
(
object
sender
, ElapsedEventArgs e )


18.
{


19.
this
.witre
(
string
.Format
(
"Run
DateTime {0}"
,
DateTime.Now ) );


20.
};


21.
}


22.


23.
protected
override
void
OnStart
(
string
[
] args )


24.
{


25.
this
.witre
(
string
.Format
(
"Start
DateTime {0}"
,
DateTime.Now ) );


26.
}


27.


28.
protected
override
void
OnStop
()


29.
{


30.
this
.witre
(
string
.Format
(
"Stop
DateTime {0}"
,
DateTime.Now ) + Environment.NewLine );


31.
}


32.


33.
void
witre
(
string
context
)


34.
{


35.
StreamWriter
sw = File.AppendText (FileName );


36.
sw.WriteLine
(context );


37.
sw.Flush
();


38.
sw.Close
();


39.
}


40.


41.
}


第2步: 添加Installer

view
sourceprint?

01.
[RunInstaller
(
true
)]


02.
public
partial
class
Installer1
: System.Configuration.Install.Installer


03.
{


04.
private
ServiceInstaller
serviceInstaller;


05.
private
ServiceProcessInstaller
processInstaller;


06.


07.
public
Installer1
()


08.
{


09.
InitializeComponent
();


10.


11.
processInstaller
=
new
ServiceProcessInstaller
();


12.
serviceInstaller
=
new
ServiceInstaller
();


13.


14.
processInstaller.Account
= ServiceAccount.LocalSystem;


15.
serviceInstaller.StartType
= ServiceStartMode.Automatic;


16.


17.
serviceInstaller.ServiceName
=
"my_WindowsService"
;


18.
serviceInstaller.Description
=
"WindowsService_Description"
;


19.
serviceInstaller.DisplayName
=
"WindowsService_DisplayName"
;


20.


21.
Installers.Add
(serviceInstaller );


22.
Installers.Add
(processInstaller );


23.
}


24.
}


第3步:安装,卸载

Cmd命令

installutil WindowsService_test.exe (安装Windows服务)

installutil /u WindowsService_test.exe (卸载Windows服务)

代码下载:http://files.cnblogs.com/aierong/WindowsService_test.rar

b.利用组件Topshelf

本方式特点:代码简单,开源组件,Windows服务可运行多个实例

Topshelf是一个开源的跨平台的服务框架,支持Windows和Mono,只需要几行代码就可以构建一个很方便使用的服务. 官方网站:http://topshelf-project.com

第1步:引用程序集TopShelf.dll和log4net.dll

第2步:创建一个服务类MyClass,里面包含两个方法Start和Stop,还包含一个定时器Timer,每隔5秒往文本文件中写入字符

view
sourceprint?

01.
public
class
MyClass


02.
{


03.
readonly
Timer
_timer;


04.


05.
private
static
readonly
string
FileName
= Directory.GetCurrentDirectory () + @
"\"
+ "
test.txt";


06.


07.
public
MyClass
()


08.
{


09.
_timer
=
new
Timer
(5000 )


10.
{


11.
AutoReset
=
true
,


12.
Enabled
=
true


13.
};


14.


15.
_timer.Elapsed
+=
delegate
(
object
sender
, ElapsedEventArgs e )


16.
{


17.
this
.witre
(
string
.Format
(
"Run
DateTime {0}"
,
DateTime.Now ) );


18.
};


19.
}


20.


21.
void
witre
(
string
context
)


22.
{


23.
StreamWriter
sw = File.AppendText (FileName );


24.
sw.WriteLine
(context );


25.
sw.Flush
();


26.
sw.Close
();


27.
}


28.


29.
public
void
Start
()


30.
{


31.
this
.witre
(
string
.Format
(
"Start
DateTime {0}"
,
DateTime.Now ) );


32.
}


33.


34.
public
void
Stop
()


35.
{


36.
this
.witre
(
string
.Format
(
"Stop
DateTime {0}"
,
DateTime.Now ) + Environment.NewLine );


37.
}


38.


39.
}


第3步:使用Topshelf宿主我们的服务,主要是Topshelf如何设置我们的服务的配置和启动和停止的时候的方法调用

view
sourceprint?

01.
class
Program


02.
{


03.
static
void
Main
(
string
[
] args )


04.
{


05.
HostFactory.Run
(x =>


06.
{


07.
x.Service<MyClass>
((s ) =>


08.
{


09.
s.SetServiceName
(
"ser"
);


10.
s.ConstructUsing
(name =>
new
MyClass
() );


11.
s.WhenStarted
((t ) => t.Start () );


12.
s.WhenStopped
((t ) => t.Stop () );


13.
}
);


14.


15.
x.RunAsLocalSystem
();


16.


17.
//服务的描述


18.
x.SetDescription
(
"Topshelf_Description"
);


19.
//服务的显示名称


20.
x.SetDisplayName
(
"Topshelf_DisplayName"
);


21.
//服务名称


22.
x.SetServiceName
(
"Topshelf_ServiceName"
);


23.


24.
}
);


25.
}


26.
}


第4步: cmd命令

ConsoleApp_Topshelf.exe install (安装Windows服务)

ConsoleApp_Topshelf.exe uninstall (卸载Windows服务)

代码下载:http://files.it165.net/pro/201205/0528ConsoleApp_Topshelf.rar

c.利用小工具instsrv和srvany

本方式特点:代码超级简单,WindowsForm程序即可,并支持程序交互(本人最喜欢的特点),好像不支持win7,支持xp win2003

首先介绍2个小工具:

instsrv.exe:用以安装和卸载可执行的服务

srvany.exe:用于将任何EXE程序作为Windows服务运行

这2个工具都是是Microsoft Windows Resource Kits工具集的实用的小工具

你可以通过下载并安装Microsoft Windows Resource Kits获得 http://www.microsoft.com/en-us/download/details.aspx?id=17657

第1步: 新建WindowsForm程序

view
sourceprint?

01.
public
partial
class
Form1
: Form


02.
{


03.
Timer
_timer;


04.


05.
private
static
readonly
string
FileName
= Application.StartupPath + @
"\"
+ "
test.txt";


06.


07.
public
Form1
()


08.
{


09.
InitializeComponent
();


10.
}


11.


12.
private
void
Form1_Load
(
object
sender
, EventArgs e )


13.
{


14.
_timer
=
new
Timer
()


15.
{


16.
Enabled
=
true
,


17.
Interval
= 5000


18.
};


19.


20.
_timer.Tick
+=
delegate
(
object
_sender
, EventArgs _e )


21.
{


22.
this
.witre
(
string
.Format
(
"Run
DateTime {0}"
,
DateTime.Now ) );


23.
};


24.
}


25.


26.
void
_timer_Tick
(
object
sender
, EventArgs e )


27.
{


28.
throw
new
NotImplementedException
();


29.
}


30.


31.
void
witre
(
string
context
)


32.
{


33.
StreamWriter
sw = File.AppendText (FileName );


34.
sw.WriteLine
(context );


35.
sw.Flush
();


36.
sw.Close
();


37.
}


38.


39.
private
void
button1_Click
(
object
sender
, EventArgs e )


40.
{


41.
MessageBox.Show
(
"Hello"
);


42.
}


43.


44.
}


第2步:安装,卸载

服务的安装步骤分5小步:

(1)打开CMD,输入以下内容,其中WindowsForms_WindowsService为你要创建的服务名称

格式:目录绝对路径\instsrv WindowsForms_WindowsService 目录绝对路径\srvany.exe

例如:

D:\TempWork\win\Debug\instsrv.exe WindowsForms_WindowsService D:\TempWork\win\Debug\srvany.exe

(2)regedit打开注册表编辑器,找到以下目录

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WindowsForms_WindowsService

(3)鼠标右键单击WindowsForms_WindowsService,创建一个"项",名称为"Parameters"

(4)鼠标左键单击"Parameters",在右边点击鼠标右键,创建一个"字符串值"(REG_SZ),名称为"Application",数值数据里填写目录下可执行文件的绝对路径+文件名

例如:

D:\TempWork\win\Debug\WindowsFormsApplication_Exe.exe

(5)打开services.msc服务控制面板,找到WindowsForms_WindowsService服务,鼠标右键-属性-登陆,勾选"允许服务与桌面交互"

启动服务,可以看到程序界面



卸载服务

D:\TempWork\win\Debug\instsrv.exe WindowsForms_WindowsService REMOVE

http://files.it165.net/pro/201205/0528WindowsFormsApplication_Exe.rar
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: