开发者

debugging windows service

开发者 https://www.devze.com 2022-12-17 10:09 出处:网络
I am trying to debug a windows service in Visual Studio 2005 on a Windows XP machine. I can install the windows service and start it from the admin console. However, the process app开发者_高级运维ears

I am trying to debug a windows service in Visual Studio 2005 on a Windows XP machine. I can install the windows service and start it from the admin console. However, the process app开发者_高级运维ears disabled in the list of available processes and I cannot attach the debugger to it. What can I do to enable the process in the list of available processes?

Thanks!


I have a little trick that allows for easy debugging. It basically turns the service into a command line application so you can debug it. Here is the code:

Add this to Program.cs (inside void Main()

#if (!DEBUG)
    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[] { new PollingService() };
    ServiceBase.Run(ServicesToRun);
#else
    // Debug code: this allows the process to run as a non-service.
    MyService service = new MyServiceService();
    service.OnStart(null);

    //Use this to make the service keep running
    // Shut down the debugger to exit
    System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);

    //Use this to make it stop
    //System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10));
    //service.OnStop();
#endif

then add this to the OnStart method in the service:

#if (!DEBUG)
    protected override void OnStart(string[] args)
#else
    public new void OnStart(string[] args)
#endif

and this to the OnStop method

#if (!DEBUG)
    protected override void OnStop()
#else
    public new void OnStop()
#endif


There are a couple of useful options here.

First I would recommend writing the Main() routine for all of your windows services to support running them either as a windows service or as a console app. That way you can run on the console for debugging much easier. A simplified Main() routine could look like this:

    private static void Main(string[] args)
    {
        _service = new Service();

        if (args.Length == 0 && !Debugger.IsAttached)
        {
            Run(new ServiceBase[] {_service});
        }
        else
        {
            Console.WriteLine("Starting Service...");
            _service.OnStart(new string[0]);
            Console.WriteLine("Service is running...  Hit ENTER to break.");
            Console.ReadLine();
            _service.OnStop();
        }
    }

You can get fancier and support different arguments for things like help, console, service, install, uninstall.

Another option is to add a Debugger.Break() statement in your code. Then you can run the service as normal and when it hits that point it will prompt the user to attach a debugger.


You probably don't have permissions to attach to the process. Make sure you have started Visual Studio from an administrative account.

0

精彩评论

暂无评论...
验证码 换一张
取 消