译者说明:我是通过翻译来学习c#的,文中涉及到的有visual studio.net有关操作,我都根据中文版的vs.net显示信息来处理的,可以让大家不致有误解。
作者:mark strawmyer
我们将研究如何创建一个作为windows服务的应用程序。内容包含什么是windows服务,如何创建、安装和调试它们。会用到system.serviceprocess.servicebase命名空间的类。
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应用程序日志当中登记下它成功启动或停止时的记录。
visual studio .net能够使创建一个windows服务变成相当简单的一件事情。启动我们的演示服务程序的说明概述如下。
1. 新建一个项目
2. 从一个可用的项目模板列表当中选择windows服务
3. 设计器会以设计模式打开
4. 从工具箱的组件表当中拖动一个timer对象到这个设计表面上 (注意: 要确保是从组件列表而不是从windows窗体列表当中使用timer)
5. 设置timer属性,enabled属性为false,interval属性30000毫秒
6. 切换到代码视图页(按f7或在视图菜单当中选择代码),然后为这个服务填加功能
在你类后面所包含的代码里,你会注意到你所创建的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]
下面就是我命名为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();
}
}
}
}
如对本文有疑问, 点击进行留言回复!!
使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序)
C#实现获取本地内网(局域网)和外网(公网)IP地址的方法分析
网友评论