调试和记录 windows 服务

Debugging and logging windows service

我正在学习 windows 服务的基础知识。我创建了一个非常简单的。

using System.ServiceProcess;

namespace WindowsServiceBasic
{
    public partial class OmerService : ServiceBase
    {
        public OmerService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            System.Diagnostics.Debugger.Launch();
            WriteLog("START");
        }

        protected override void OnStop()
        {
            System.Diagnostics.Debugger.Launch();
            WriteLog("STOP");
        }

        private void WriteLog(string durum)
        {
            eventLog1.WriteEntry(performanceCounter1.RawValue.ToString());
        }
    }
}

using System;
using System.IO;
using System.ServiceProcess;

namespace WindowsServiceBasic
{
    internal static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        private static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new OmerService()
            };
            ServiceBase.Run(ServicesToRun);
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if (e != null && e.ExceptionObject != null)
            {
                string createText = e.ToString();
                File.WriteAllText(@"c:\omerlog.txt", createText);
            }
        }
    }
}

我的服务(AServis)第一次成功启动,但是当我点击重启时它崩溃了。由于我的服务很简单,所以应该可以正常使用。我尝试记录错误,尝试捕获但我找不到任何东西。我正在尝试附加进程,它调试停止事件但在停止调试后突然完成并启动进程崩溃。你能帮我看看是什么原因吗?我该如何调试和记录错误。

提前致谢

我在这种情况下使用的标准技巧是在我的启动代码中添加对 System.Diagnostics.Debugger.Break 的调用。现在,当您正常启动服务时(通过服务控制管理器 (SCM)),对 Break 的调用将导致 Windows 启动 JIT 调试器,这会提示您选择要附加的调试器到进程(例如,Visual Studio),这将使您能够正常调试代码。

另请参阅:Easier way to debug a Windows service

我看到卡在了

public OmerService()
{
    InitializeComponent();
}

我可以看到添加 System.Diagnostics.Debugger.Launch() 的问题;声明。

public OmerService()
{
    System.Diagnostics.Debugger.Launch();
    InitializeComponent();
}