一个最简单的windows service的建立

来源:互联网 发布:淘宝店铺导航条装修 编辑:程序博客网 时间:2024/05/18 02:12

利用vs.net我们可以在几分钟之内建立其windows服务,非常简单

下面说一下步骤
1. 新建一个项目
2. 选择Windows服务
3.从工具箱的组件表当中拖动一个Timer对象到这个设计表面上,使用的的system.timer.time 
4. 设置Timer属性,Interval属性200毫秒(1秒进行5次数据库操作)
5.双击这个Timer,然后在里面写一些数据库操作的代码,比如
 SqlConnection conn=new SqlConnection("server=127.0.0.1;database=test;uid=sa;pwd=275280");
   SqlCommand comm=-new SqlCommand("insert into tb1 values ('111',11)",conn);
   conn.Open();
   comm.ExecuteNonQuery();
   conn.Close();

6. 将这个服务程序切换到设计视图
7. 右击设计视图选择“添加安装程序”
8. 切换到刚被添加的ProjectInstaller的设计视图
9. 设置serviceInstaller1组件的属性: 
    1) ServiceName = My Sample Service
    2) StartType = Automatic (开机自动运行)
10. 设置serviceProcessInstaller1组件的属性  Account = LocalSystem
11. 改变路径到你项目所在的bin/Debug文件夹位置(如果你以Release模式编译则在bin/Release文件夹)
12. 执行命令“InstallUtil.exe MyWindowsService.exe”注册这个服务,使它建立一个合适的注册项。(InstallUtil这个程序在WINDOWS文件夹/Microsoft.NET/Framework/v1.1.4322下面)
13. 右击桌面上“我的电脑”,选择“管理”就可以打计算机管理控制台
14. 在“服务和应用程序”里面的“服务”部分里,你可以发现你的Windows服务已经包含在服务列表当中了
15. 右击你的服务选择启动就可以启动你的服务了
============================

这个service设计定时器的问题
C#中有3个timer类
1.定义在System.Windows.Forms里
2.定义在System.Threading.Timer类里
3.定义在System.Timers.Timer类里

System.Windows.Forms.Timer是应用于WinForm中的,它是通过Windows消息机制实现的,类似于VB或Delphi中的Timer控件,内部使用API SetTimer实现的。它的主要缺点是计时不精确,而且必须有消息循环,Console Application(控制台应用程序)无法使用。

System.Timers.Timer和System.Threading.Timer非常类似,它们是通过.NET Thread Pool实现的,轻量,计时精确,对应用程序、消息没有特别的要求。System.Timers.Timer还可以应用于WinForm,完全取代上面的Timer控件。它们的缺点是不支持直接的拖放,需要手工编码。

例:
使用System.Timers.Timer类
System.Timers.Timer t = new System.Timers.Timer(10000);//实例化Timer类,设置间隔时间为10000毫秒;
t.Elapsed += new System.Timers.ElapsedEventHandler(theout);//到达时间的时候执行事件;
t.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;

public void theout(object source, System.Timers.ElapsedEventArgs e)
{
MessageBox.Show("OK!");  //不能有界面,没有反映
string path = @"e:/MyTest.txt";

            try
            {
                string textLine = "This is some text in the file." + DateTime.Now.ToString() + "/r/n";
                File.AppendAllText(path, textLine);
            }

            catch (Exception Ex)
            {
                return;
            }

 

原创粉丝点击