How do you debug a Windows Service?

后端 未结 15 2819
春和景丽
春和景丽 2020-12-12 21:07

I read the MSDN article on the topic. To quote:

Because a service must be run from within the context of the Services Control Manager rather than

15条回答
  •  庸人自扰
    2020-12-12 21:36

    One thing I do (which may be kind of a hack) is put a Thread.Sleep(10000) right at the beginning of my OnStart() method. This gives me a 10-second window to attach my debugger to the service before it does anything else.

    Of course I remove the Thread.Sleep() statement when I'm done debugging.

    One other thing you may do is the following:

    public override void OnStart()
    {
        try
        {
            // all your OnStart() logic here
        }
        catch(Exception ex)
        {
            // Log ex.Message
            if (!EventLog.SourceExists("MyApplication"))
                EventLog.CreateEventSource("MyApplication", "Application");
    
            EventLog.WriteEntry("MyApplication", "Failed to start: " + ex.Message);
            throw;
        }
    }
    

    When you log ex.Message, you may get a more detailed error message. Furthermore, you could just log ex.ToString() to get the whole stack trace, and if your .pdb files are in the same directory as your executable, it will even tell you what line the Exception occurred on.

提交回复
热议问题