2

Windows サービスでタイマーを使用しようとしています。サービスは開始および停止でき、これが発生したときにイベント ログに何かを書き込みます。これは機能します。私の問題は、timeElapsed イベントが発生するたびに実行し続けるタイマーを使用し、イベント ログに何かを書き込みたいということです。

編集:(コードを変更したため、タイマーはフィールドですが、それでも期待した結果ではなく、イベント ログにログ エントリがありません)

using System.Timers;

サービスの初期化:

    public Timer timer;

    public MonitorService()
    {
        InitializeComponent();
        timer = new Timer(10000);
        //Some code that really doesn't matter
    }

開始時のイベント

    protected override void OnStart(string[] args)
    {
        // Hook up the Elapsed event for the timer.
        timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        timer.Enabled = true;

        timer.Start();

        EventLogger.WriteEntry("Biztalk monitoring service started", EventLogEntryType.SuccessAudit);

        // If the timer is declared in a long-running method, use
        // KeepAlive to prevent garbage collection from occurring
        // before the method ends.
        // GC.KeepAlive(timer);
    }


    private int count =0;

時間指定イベント: (これは機能しません。10 秒ごとにイベント ログに書き込まれるエントリはありませんが、期待どおりです)

    // Specify what you want to happen when the Elapsed event is 
    // raised.
    private void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        //Some other code that doesn't mather
        count++;
        EventLogger.WriteEntry(string.Format("TimerEvent has ran {0} times. Total time is: {1}", count, e.SignalTime), EventLogEntryType.Information);
    }

停止イベント:

    protected override void OnStop()
    {
        EventLogger.WriteEntry("Biztalk monitoring service stopped", EventLogEntryType.Warning);
    }

主要

これが私の Program.cs での主なメソッドであることに疑問を持っている人のために:

     ///<summary>
     ///The main entry point for the application.
     ///</summary>
    static void Main()
    {
        var servicesToRun = new ServiceBase[] 
            { 
                new MonitorService() 
            };
        ServiceBase.Run(servicesToRun);
    }

すでに尋ねましたか?はい、そうです!

私は、この質問が以前に次のように尋ねられたことを認識しています: Windows service with timer AND Best Timer for using in a Windows service

しかし、これらの解決策は私の問題を解決していないようです。

どんな提案も大歓迎です!

4

2 に答える 2

0

一定時間経過後にイベントログに何かを記録したい場合(使用しているタイマーの経過イベントで行っていること以外)、サービスレベルで別のタイマーを使用して経過イベントを登録することができます。その場合、必要なものは何でもログに記録できます。

nvoigt が述べたように、このタイマーもサービスレベルに移動する必要があります。

于 2013-05-15T09:59:42.387 に答える