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 並未鎖定。
這段代碼有什麼問題?
爲什麼計時器調用此方法時狀態不同?