簡體   English   中英

Windows 服務定時器多線程

[英]Windows service timer multithread

我正在構建一個 Windows 服務,它將根據數據庫中的時間表審核用戶。 該服務每十分鍾檢查一次數據庫的計划審計。 一旦審計開始,它會在數據庫表中標記一個開始時間,因此如果超過十分鍾就不會再次開始。

我的問題是,以下代碼對於我正在做的事情是否可以接受,我是否應該在每次 10 分鍾后使用多線程,如果是這樣,我將如何做到這一點?

我的示例代碼:

protected override void OnStart(string[] args)
{
    var aTimer = new Timer(600000);
    aTimer.Elapsed += ATimerElapsed;
    aTimer.Interval = 600000;
    aTimer.Enabled = true;
    GC.KeepAlive(aTimer);
}

private static void ATimerElapsed(object sender, ElapsedEventArgs e)
{
    try
    {
         Worker.ProcessScheduledAudits();
    }
    catch (Exception ex)
    {
         EventLog.WriteEntry("Application", ex.Message, EventLogEntryType.Error);
    }                
}

System.Threading.Timer 將使用 Threadpool 中的線程來運行 Elapsed 處理程序。 因此,您已經通過使用計時器來使用多線程。 事實上,所有的定時器都使用某種后台線程。 他們只是在如何多線程上有所不同,以便執行對預期用途最有意義的事情。

如果您需要每十分鍾運行一次,但還要確保兩個處理程序不會同時運行,請嘗試在 Elapsed 方法中設置“CurrentlyRunning”標志,並在執行任何繁重工作之前對其進行檢查。

    protected override void OnStart(string[] args)
    {
        var aTimer = new Timer(600000);
        aTimer.Elapsed += ATimerElapsed;
        aTimer.Interval = 600000;
        aTimer.Enabled = true;
        GC.KeepAlive(aTimer);
    }

    private static currentlyRunning;

    private static void ATimerElapsed(object sender, ElapsedEventArgs e)
    {
        if(currentlyRunning) return;
        currentlyRunning = true;
        try
        {
            Worker.ProcessScheduledAudits();
        }
        catch (Exception ex)
        {
            EventLog.WriteEntry("Application", ex.Message, EventLogEntryType.Error);
        }
        currentlyRunning = false;
    }

從理論上講,這可能會進行比賽,但是由於您每 10 分鍾才為該事件啟動一個線程,因此可能性極小。

這段代碼已經“使用多線程”。 假設您的Timer實例是System.Timers.Timer ,您的Elapsed處理程序將在線程池線程上運行。

如果這不是您想要的,您可以使用SynchronizingObject屬性來修改調度行為。 有關更多詳細信息,請閱讀MSDN 文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM