2012-04-04 74 views
1

我想在一個應該以固定的時間間隔執行動作的Windows服務中使用計時器而不是睡眠。在Windows服務中使用計時器

可以說我有以下班級。

class MailManagerClient 
{ 

    //fields 
    string someString 

    //Constructor 
    public MailManagerClient() 
    { 
      aTimer = new System.Timers.Timer(30000); 
      aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); 
      aTimer.Enabled = true 
    } 
    //methode 

    public bool DoSomthingIncConstantInterval() 
    { 
     //Do Somthing 
     return true; 
    } 


    private static void OnTimedEvent(object source, ElapsedEventArgs e) 
    { 
     DoSomthingIncConstantInterval() 
    } 
} 

而且我也有與OnStart方法的窗口服務。

我知道在OnStart方法中,我需要爲類型MailManagerClient啓動一個新線程。

但我該如何啓動線程?哪個方法應該是新線程的入口點?

該線程應該如何保持活動狀態?

+0

也許你應該看看quartz.net,我認爲它會更好地爲你的目的服務。 – alxbrd 2012-04-04 15:21:15

+0

[System.Reactive.Linq](http://msdn.microsoft.com/zh-cn/library/hh229435(v = vs.103).aspx)中的Observable.Timer也是其他內容。 – 2012-04-04 15:22:55

回答

1

因爲你開始在構造比你真正需要做定時器是實例化一個OnStartMailManagerClient。您不需要手動創建線程,因爲System.Timers.TimerThreadPool的線程上執行Elapsed事件處理程序。

public class MyService : ServiceBase 
{ 
    private MailManagerClient mmc = null; 

    protected void OnStart(string[] args) 
    { 
    mmc = new MailManagerClient(); 
    } 

} 

我應該指出,這將不是很明顯的下一個程序員看你的代碼MailManagerClient.ctor實際上是做任何事情。最好定義一個Start方法或類似的啓用內部定時器的方法。

1

在OnStart方法,你可以有 -

MailManagerClient m; 
var th = new Thread(()=>m=new MailManagerClient()); 
th.Start();