首页 > 解决方案 > 如何检测 Windows 服务是否已崩溃?

问题描述

我安装了 Windows 服务,它正在运行。

当系统关闭时,我写入事件日志条目,但是代码不会在系统关闭或重新启动时写入事件日志。

protected override void OnShutdown()   
{  
    WriteToEventLog("Services shut down.");       
}

private void WriteToEventLog(string logMessage)
{
    var mySource = "MySourceLog";
    // Create the source and log, if it does not already exist.
    if (!EventLog.SourceExists(mySource))
    {
        EventLog.CreateEventSource(mySource, mySource); 
    }
    // Create an EventLog instance and assign its source.
    using (var eventLog = new EventLog())
    {
        eventLog.Source = mySource;
        // Write an entry to the event log.
        eventLog.WriteEntry(logMessage, EventLogEntryType.Warning, 1002);
    }
}

每当我的 Windows 服务崩溃时,我想将一个事件写入事件日志,并可能发送一封电子邮件作为警报,说明该服务已崩溃。我如何检测到该服务已崩溃并将其写入事件日志?

标签: c#.netwinformsservicewindows-services

解决方案


推荐阅读