2016-03-06 93 views
0

我在asp.net頁後面的代碼:如何正確使用Timer對象?

protected void LoadFile(object sender, EventArgs e) 
    { 
     try 
     { 
       Timer myTimer = new Timer(); 
       myTimer.Elapsed += new ElapsedEventHandler(RemoveFile); 
       myTimer.Interval = 60000; 
       myTimer.Start(); 
     } 
     catch (Exception) 
     { 
     } 
    } 

    private void RemoveFile(object source, ElapsedEventArgs e) 
    { 
      string path = UniquePath(); 
      File.Delete(path); 
    } 

當的LoadFile事件處理程序60發射秒,如果經過的LoadFile再次發射(因爲這行myTimer.Interval = 60000中所定義)之後的RemoveFile功能燒製40秒後,RemoveFile將在20秒內觸發。

我的問題是如何使RemoveFile函數在上次調用LoadFile事件處理程序60秒後激活?

+0

'如果LoadFile在40秒後再次觸發,則RemoveFile將在20秒內觸發。「 - 您的意思是'RemoveFile'在那個時候會被調用兩次? (第一次通話後一分鐘,第二次後20秒)?或者它只會被調用一次? – Rob

+3

請不要編寫'catch(Exception)',更不用說'catch(Exception){}'。這是一個隱藏錯誤的不良做法。 – Enigmativity

+0

@Rob它只會被調用一次 – Michael

回答

0

可能是你可以使用 myTimer.Stop();剛過Timer myTimer = new Timer();

0

我會使用微軟的反應擴展(的NuGet「RX-主」)這一點。代碼變爲:

private SerialDisposable _serialDisposable = new SerialDisposable(); 

protected void LoadFile(object sender, EventArgs e) 
{ 
    _serialDisposable.Disposable = 
     Observable 
      .Interval(TimeSpan.FromSeconds(60.0)) 
      .Subscribe(n => 
      { 
       string path = UniquePath(); 
       File.Delete(path) 
      }); 
} 

現在,觀測是一樣的事件,並呼籲.Subscribe就像是連接到一個事件。 .Subscribe調用返回IDisposable,通過調用.Dispose()可以使用該調用來從觀察值中分離。 SerialDisposable對象是由Rx提供的一種特殊的一次性類,可讓您分配新的一次性物品並自動處理先前分配的一次性物品。這會在每次運行LoadFile時自動重置計時器。

這只是Rx的一個用途 - 它有更多的用途,功能非常強大,值得學習。

+0

但是LoadFile是asp.net中的asp.net事件處理程序。所以如果我創建serialDisposable作爲類變量,它將在每次回發調用中重新創建。 – Michael

+0

@Michael你可以把它放在一個會話變量中。或者在一個靜態集合中加載/根據你的邏輯創建'_serialDisposable'。 – Rob