事件处理程序应放在Windows服务中的哪个位置?

时间:2016-08-14 23:55:39

标签: c# events service

我正在尝试将控制台应用程序项目转换为Windows服务。

我的虚拟控制台应用项目正在侦听来自第三方API(NET2 sdk)的访问事件,并将其信息打印到控制台。我想将它转换为在后台作为Windows服务运行。

但是我很难保持事件处理程序“活着”,因此它会在服务运行时继续捕获访问事件。

目前我已将它放在onStart()函数中,如下所示:

Net2 net2;

public Net2MonitoringService()
{
    InitializeComponent();
    eventLog1 = new System.Diagnostics.EventLog();
    if (!System.Diagnostics.EventLog.SourceExists("Net2 Monitoring Service"))
    {
        System.Diagnostics.EventLog.CreateEventSource(
            "Net2 Monitoring Service", "Net2 Monitoring Log");
    }
    eventLog1.Source = "Net2 Monitoring Service";
    eventLog1.Log = "Net2 Monitoring Log";
}

  protected override void OnStart(string[] args)
    {
        eventLog1.WriteEntry("Net2 Monitoring Service has started.");
        net2 = new Net2();
        net2.Login();

        //Monitor main door events
        net2.client.MonitorAcu(1172079);
        eventLog1.WriteEntry("Monitoring door #1172079. Listening for events...", EventLogEntryType.Information);

        //Create an event handler to handle the access event
        net2.client.Net2AccessEvent += new OemClient.Net2AcuEventHandler(Net2AccessEvent);
    }

    protected override void OnStop()
    {
        net2.Logout();
        eventLog1.WriteEntry("Net2 Monitoring Service has stopped.");
    }

    private void Net2AccessEvent(object sender, IEventView e)
    {
        //Print access event details to log
        string message = "Access event triggered:\n" +
            "UserId: " + e.UserId.ToString() + "\n" +
            "EventId: " + e.UserId.ToString() + "\n" +
            "Address: " + e.UserId.ToString() + "\n" +
            "SubAddress: " + e.UserId.ToString() + "\n" +
            "EventDateTime: " + e.UserId.ToString() + "\n";
        eventLog1.WriteEntry(message, EventLogEntryType.SuccessAudit);
    }

上述代码导致永远不会触发Net2AccessEvent方法,即使有要捕获的事件也是如此。

PS:当从Visual Studio调试器触发时,相同的代码在控制台应用程序的Main()内执行时工作正常,使主线程保持活动状态。

1 个答案:

答案 0 :(得分:0)

要在几天后回答我自己的问题,在使用单例以避免丢失监视范围并在OnStart()方法上运行它之后,问题似乎得到了解决。