2016-02-18 38 views
0

我想創建一個函數,定期調用(1秒),該函數可能需要超過1秒鐘。如果函數未完成,則不應創建新線程。如果它完成,它應該等到時間。哪種計時器方法是C#中最好的解決方案?C#中的同步定時器回調#

回答

0
Timer timer = new Timer();//Create new instance of "Timer" class. 
timer.Interval = 1000;//Set the interval to 1000 milliseconds (1 second). 
bool started = false;//Set the default value of "started" to false; 
timer.Tick += (sender, e) =>//Set the procedure that occurs each second. 
{ 
    if (!started)//If the value of "started" is false (if it isn't running in another thread). 
    { 
     started = true;//Set "started" to true to ensure that this code isn't run in another thread. 
     //Other code to be run. 
     started = false;//Set "started" to false so that the code can be run in the next thread. 
    } 
}; 
timer.Enabled = true;//Start the timer. 
0

使用微軟的反應擴展(的NuGet 「RX-主」),你可以這樣做:

Observable 
    .Interval(TimeSpan.FromSeconds(1.0)) 
    .Subscribe(n => 
    { 
     /* Do work here */ 
    }); 

它等待認購調用之間的時間間隔。

+0

不管這個線程是否已經完成,這個不會運行嗎? – Rariolu

+0

@Rariolu - 不,它不是'Timer',它是'Interval'。它等待運行每個訂閱之間的差距。 – Enigmativity