最近第一次用C#写了一个windows service ,其实实现的内容比较简单。就是启动remoting 连接,但是调试相对初次写windws service 的我来说,比较烦。没有经验,而且没办法像调试其他windows 程序一样设置断点,无法看到运行过程。经过查看一些相关资料后,有了一点点调试的心得。特此留笔,以待今后使用。
 
相关源码:

static void Main()
        {
            ServiceBase[] ServicesToRun;

// 同一进程中可以运行多个用户服务。若要将
            // 另一个服务添加到此进程中,请更改下行以
            // 创建另一个服务对象。例如,
            //
            //   ServicesToRun = new ServiceBase[] {new Service1(), new MySecondUserService()};
            //
            ServicesToRun = new ServiceBase[] { new TeamWorldService() };

ServiceBase.Run(ServicesToRun);
            //TeamWorldService obj = new TeamWorldService();
            //obj.OnStart();
        }

TeamWorldService :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
using Tribal.TeamWorld.API;
using Tribal.BaseClasses;
using Tribal.TeamWorld.Remoting;
using Tribal.TeamWorld.Implementation;

namespace Tribal.TeamWorld.Service
{
    partial class TeamWorldService : ServiceBase
    {
        private RemotingInterface _remotingInterface = null;
        private MainController _mainController = null;
        public TeamWorldService()
        {
            InitializeComponent();//
            
        }

protected override  void OnStart(string[] args)
        {
            this.AddTextLine("Starting server  ( " + DateTime.Now.ToString() + " )");

try
            {
                this.AddTextLine("Initializing MainController ");
                this._mainController = MainController.GetInstance();
            }
            catch (Exception ex)
            {
                this.PrintExceptions(ex);
            }

if (this._mainController != null)
            {
                this.AddTextLine("Connecting userinterface to LogController ");
            }

try
            {
                this.AddTextLine("Starting MainController");
                this._mainController.Start();
            }
            catch (Exception exc)
            {
                this.PrintExceptions(exc);
            }

try
            {
                this.AddTextLine("Starting .NET RemotingInterface");
                this._remotingInterface = new RemotingInterface();
                this._remotingInterface.StartServing();
            }
            catch (Exception exc)
            {
                this.PrintExceptions(exc);
            }
        }

protected override void OnStop()
        {
            
            this._remotingInterface.StopServing();
            this._mainController.Stop();
            this.AddTextLine("End .NET RemotingInterface");
            
        }

private void PrintExceptions(Exception exc)
        {
            Exception current = exc;
            while (current != null)
            {
                this.AddTextLine(current.Message);
                this.AddTextLine(current.StackTrace);

current = current.InnerException;
            }
        }

private void AddTextLine(string line)
        {
            try
            {
                FileStream fs = new FileStream(@"C:\TeamWorldServiceLog.txt", FileMode.OpenOrCreate, FileAccess.Write);

StreamWriter m_streamWriter = new StreamWriter(fs);

m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);

m_streamWriter.WriteLine(line+ "\r\n");

m_streamWriter.Flush();

m_streamWriter.Close();

fs.Close();
            }
            catch (Exception ex)
            { 
                
            }
        }
    }
}

方法1:写日志
        是最传统的调试windows service方法,也是大家在调试service 比较管用的方式,但是,调试起来还是不太明朗。你要在你认为可能出现错误的地方全部添加写日志的方法。我上面的代码就采用了AddTextLine 函数实现的这种方法。

方法2:附加进程
        附加进程的方法可以像调试正常的widows程序一样,设置断点进行单步调试。但是,我必须在安装启动服务后,才可以进行附加此服务进程,可在附加的同时OnStart 函数已经执行完毕,所以对Onstart 无法调试。但是我可以通过设置启动服务延时来加载调试。
        步骤如下:
                     1,设置启动服务延时,


private System.Timers.Timer timerDelay;

        protected override void OnStart(string[] args)
        {
            try
            {
                
                ///delay start the SynData 30seconds
                timerDelay = new System.Timers.Timer(30000);   
                timerDelay.Elapsed += new System.Timers.ElapsedEventHandler(timerDelay_Elapsed);
                timerDelay.Start();
            }
            catch (Exception ex)
            {
                this.PrintExceptions(ex);
            }
        }         void timerDelay_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            timerDelay.Enabled = false;
            timerDelay.Close();
            //你要加的代码
            //.To do..
        }

注意:正常服务的启动时间为30秒左右,当服务启动时间超过30秒会报错!,所以不要在OnStart中做过多的操作,也可以用这种延时的方法启动服务,以防在启动服务时超时。
                     2、首先要对服务进行安装,然后启动服务。
                     3、打开vs2005  调试—>附加到进程,选择你的服务进程(如果找不到可以勾选 显示所有用户的进程),就可以了。
                        
方法3:
      我认为是这次调试对我帮助最大。
      在Main 函数中,注释掉原有自动生成的代码,注意红字部分是要根据自己的服务名字来手工添加的
             // ServiceBase[] ServicesToRun;

// 同一进程中可以运行多个用户服务。若要将
            // 另一个服务添加到此进程中,请更改下行以
            // 创建另一个服务对象。例如,
            //
            //   ServicesToRun = new ServiceBase[] {new Service1(), new MySecondUserService()};
            //
            //ServicesToRun = new ServiceBase[] { new TeamWorldService() };

//ServiceBase.Run(ServicesToRun);
            //******************************************
            TeamWorldService obj = new TeamWorldService();
            obj.OnStart();
            //******************************************
      然后把 protected override  void OnStart(string[] args) 改为 public void OnStart()。
      ,设置你的断点,按 F5 运行就可以调试了。

以上是自己这次调试widows service 后,得到的一些方法。以待今后继续积累。

http://www.cnblogs.com/peak-weng/archive/2008/05/30/1210538.html

windows Service 之调试过程(附加到进程里调试,而且启动时间不能超过30秒)的更多相关文章

  1. VS·调试过程中某个操作导致调试突然退出之解决方案

    阅文时长 | 0.11分钟 字数统计 | 232字符 主要内容 | 1.引言&背景 2.声明与参考资料 『VS·调试过程中某个操作导致调试突然退出之解决方案』 编写人 | SCscHero 编 ...

  2. vs中附加IIS进程的调试方法

    项目运行以管理员的身份进行运行否则附加不进去:

  3. windows service(system权限)创建用户权限进程

    windows编程的人都知道,在其操作系统下,进程被创建,通常被赋予很多属性,其中一项属性就是用户名,及进程所属的权限.打开任务管理器,可查看到. 通常桌面系统explorer的权限是User权限,即 ...

  4. C# Windows Service服务的创建和调试

    前言 关于Windows服务创建和调试的文章在网络上的很多文章里面都有,直接拿过来贴在这里也不过仅仅是个记录,不会让人加深印象.所以本着能够更深刻了解服务项目的创建和调试过程及方法的目的,有了这篇记录 ...

  5. 调试Windows Service

    调试Windows Service 使用一般的调试方法调试不了Windows Servers,所以参考了一些调试方法 我服务源码中使用了Timer,注意不能使用工具箱内的Timer,用System.T ...

  6. OpenCV dll 源码调试—附加到进程

    使用CMake可以生成OpenCV源码的解决方案,然后就可以对OpenCV函数进行修改,功能剪切等操作了,对这部分内容感兴趣的可以浏览一下上一篇文章:CMake生成OpenCV解决方案&&am ...

  7. ASP.NET Core Web 应用程序开发期间部署到IIS自定义主机域名并附加到进程调试

    想必大家之前在进行ASP.NET Web 应用程序开发期间都有用到过将我们的网站部署到IIS自定义主机域名并附加到进程进行调试. 那我们的ASP.NET Core Web 应用程序又是如何部署到我们的 ...

  8. 四、附加到进程调试(.NET Framework)

    附加到进程调试: 1.需要在IIS配置环境并可运行即通过浏览器可打开. 2.找到项目w3wp.exe进程并附加到进程调试,点击项目添加断点,直接访问浏览器即可. 优点:w3wp.exe是已经运行的,调 ...

  9. C#使用附加到进程调试

    微软官网的调试进程介绍 首先运行bin下的可执行文件,然后打开源代码,选择调试--->附加到进程.

随机推荐

  1. 已解决!Fatal error compiling: 无效的标记(maven启动失败)

    问题描述 Fatal error compiling: 无效的标记 maven启动错误..版本号不对 <plugin> <artifactId>maven-compiler-p ...

  2. Zero Downtime Upgrade of Oracle 10g to Oracle 11g Using GoldenGate — 1

    Source Database DB Name:        zwc Schemas:         HR,OE,PM Version:          10.2.0.4 RAC:       ...

  3. 利用WPF建立自己的3d gis软件(非axhost方式)(六)跳转,增加外部三维模型

    原文:利用WPF建立自己的3d gis软件(非axhost方式)(六)跳转,增加外部三维模型 先下载SDK:https://pan.baidu.com/s/1M9kBS6ouUwLfrt0zV0bPe ...

  4. 采用navicat导出表结构及数据insert声明

    旧navicat有一段时间,查找navicat真的很方便,它可以支持各种数据库的. 他一直认为无处不在sql文件比较麻烦,每个表会生成一个sql档,不方便开展进口业务.今天,它已突然发现了一个批次sq ...

  5. Android 开发新方向 Android Wear ——概述

    2014 谷歌 I/O大会正式公布的Android Wear 开发理念,从而能够更系统的提供开发人员使用Android接口开发便携式可穿戴设备,以智能手表为例,通过Android提供的接口,能够方便的 ...

  6. Android子线程中更新UI的4种方法

    方法一:用Handler 1.主线程中定义Handler: Handler mHandler = new Handler() { @Override public void handleMessage ...

  7. 3 Task中的一些枚举 创建时候的、continue时候的

    创建时常用的枚举: None.PreferFairness.LongRunning.AttacthedToParent.DenyChildAttach.HideScheduler AttacthedT ...

  8. ASP.NET Core Razor 视图起始页 - ASP.NET Core 基础教程 - 简单教程,简单编程

    原文:ASP.NET Core Razor 视图起始页 - ASP.NET Core 基础教程 - 简单教程,简单编程 ASP.NET Core Razor 视图起始页 上一章节中我们介绍了布局视图, ...

  9. hdoj 5087 Revenge of LIS II 【第二长单调递增子】

    称号:hdoj 5087 Revenge of LIS II 题意:非常easy,给你一个序列,让你求第二长单调递增子序列. 分析:事实上非常easy.不知道比赛的时候为什么那么多了判掉了. 我们用O ...

  10. 数据绑定(三)为Binding指定绑定源的几种方法

    原文:数据绑定(三)为Binding指定绑定源的几种方法 Binding的源是数据的来源,所以,只要一个对象包含数据并能通过属性把数据暴露出来,它就能当作Binding的源来使用,常用的办法有: 一. ...