首页 > 技术文章 > Windows服务工程创建、部署

Extreme 2014-04-02 21:42 原文

一、创建、部署windows服务

1.在VS2010创建windows service工程

文件---新建---项目----windows服务。

                       

2.双击service1.cs,在onstart中写具体代码,注意如果代码执行需要很长时间,则需要将方法放在子线程中否则windows服务会启动不起来

 

        protected override void OnStart(string[] args)
        {
            try
            {
                log4.Info("服务已启动:");
                ExecuteTimerTask();
            }
            catch (Exception ex)
            {
                log4.Error("服务启动失败", ex);
            }
        }
View Code

 

3.定时器Quartz的使用

 

        public void ExecuteTimerTask()
        {
            //初始化委托变量
            TimerTaskDelegate task = new TimerTaskDelegate(SpaceTask);

            //创建定时任务线程并启动
            Thread ThreadTimerTask = TimerTask.CreateTimerTaskThread(task);
            ThreadTimerTask.IsBackground = true;
            ThreadTimerTask.Start();
            log4.Info("定时任务已启动:");
        }
View Code

 

4.添加安装程序

在PageRequestService.cs[设计]右键---添加安装程序,会出现

注意:account选择localhost  ;StartType选择Automatic(开机自动执行)

 

5.安装服务

管理员身份运行cmd,执行以下命令

 

开始-运行-cmd

 

安装命令

C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe C:\PageRequestService\PageRequestService.exe

 

卸载命令

C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe C:\PageRequestService\PageRequestService.exe -u

 

在控制面板---管理工具-----服务----右键----启动服务

 

6.异常情况

如果不能正常启动服务,说明服务有错误。可以利用“日志查看器”查看错误信息。(调试比较麻烦)。

注意每次对服务改动的话,都必须重新安装。

 

二、部署出错处理AutoLog设置:

安装时报错如下:

An exception occurred during the Install phase.

System.InvalidOperationException: Cannot open Service Control Manager on computer '.'. This operation might require other privileges.

The inner exception System.ComponentModel.Win32Exception was thrown with the following error message: 拒绝访问。.

 

The Rollback phase of the installation is beginning.

See the contents of the log file for the C:\PageRequestService\bin\Debug\PageRequestService.exe assembly's progress.

The file is located at C:\PageRequestService\bin\Debug\PageRequestService.InstallLog.

 

The Rollback phase completed successfully.

 

The transacted install has completed.

 

由于自动写系统日志时出错(例如没有权限),因此将WindowsService的AutoLog属性设为false,即可完成安装。

 

 

源码下载:WinService Source

 

 

推荐阅读