2016-03-04 56 views
0

我有一些Timer的問題。C#調用timer.Elapsed方法,並點擊

這是我的代碼:

_uploadHelper = new DataProcessorUploadHelper((sender, args) => Start()) 

public void Start() 
{ 
     Task.Factory.StartNew(() => 
     { 
      if (UploadHelper.UploadState == UploadState.UploadOn) 
      { 
       UploadHelper.IncrementSavingRequestCounter(); 
      } 
      else 
      { 
       UploadHelper.StopTimer(); 
       lock (_lock) 
       { 
        UploadHelper.UploadState = UploadState.UploadOn; 

        UploadData(); 

        UploadHelper.UploadState = UploadState.UploadOff; 
       } 
       UploadHelper.StartTimer(); 
      } 
     }); 
} 

UploadState以這種方式

private int _uploadState; 

    public UploadState UploadState 
    { 
     get { return (UploadState)_uploadState; } 
     set { Interlocked.Exchange(ref _uploadState, (int)value); } 
    } 

我使用System.Timers.Timer應該調用Start方法與間隔10分鐘(中實現實施在我的幫手類中)。

private Timer _intervalTimer; 
    private long _savingRequestsCounter; 

    public DataProcessorUploadHelper(ElapsedEventHandler callback) 
    { 
     UploadState = UploadState.UploadOff;; 
     _intervalTimer = new Timer(); 
     _intervalTimer.Interval = UploadIntervalTimeSpan.TotalMilliseconds; 
     _intervalTimer.Elapsed += callback; 
     _intervalTimer.Start(); 
     _intervalTimer.Enabled = true; 
    } 
    public void StartTimer() 
    { 
     _intervalTimer.Start(); 
    } 
    public void ResetTimer() 
    { 
     _intervalTimer.Start(); 
     _intervalTimer.Stop(); 
    } 

    public void StopTimer() 
    { 
     _intervalTimer.Stop(); 
    } 
    public void IncrementSavingRequestCounter() 
    { 
     Interlocked.Increment(ref _savingRequestsCounter); 
    } 

    public void DecrementSavingRequestCounter() 
    { 
     Interlocked.Decrement(ref _savingRequestsCounter); 
    } 

此外,當用戶單擊特定按鈕時也調用此方法。

還有我的麻煩。

定時器調用Start方法=> UploadHelper.UploadState = UploadState.UploadOn。

此外應該鎖定_lock。

但是,當用戶在UploadData() 期間點擊時,我看到UploadState = UploadState.UploadOff 並未鎖定。

這段代碼有什麼問題?

爲什麼計時器調用此方法時狀態不同?

回答

1
  1. 「......而且應該由_lock鎖定」

是如果_lock被聲明爲你的情況靜態

由於Timer的Elapsed-Event導致在單獨的線程中調用UploadData(),_lock(如果不是靜態的)每次都不是同一個_lock,並且不用作同步對象。

  • 如果定時器是從System.Timers,然後還存在另一種方法來進行同步: 看到SynchronizingObject