我告訴Timer在構造函數中啓動。它開始,但是當它到達Timer.Elapsed事件時,它只運行方法中的第一個if語句。我已檢查isWatching
是否屬實,它是,但它仍然完全跳過它。它甚至沒有達到if(isWatching)
系列。C#定時器跳過代碼
代碼:
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
public SessionManager SM { get; private set; }
public MainWindow()
{
SM = new SessionManager();
SM.NewDayEvent += SplitSession;
///code
}
}
SessionManager.cs(有些變量已經從這篇文章中省略):
public class SessionManager : INotifyPropertyChanged
{
public delegate void NewDayEventHandler(object sender, EventArgs ea);
public event NewDayEventHandler NewDayEvent;
private bool _isWatching;
private Timer _timer;
private bool isWatching
{
get
{
return _isWatching;
}
set
{
_isWatching = value;
if (!_isWatching)
{
_clockWatch.Stop();
}
else
{
_clockWatch.Start();
}
}
}
#endregion
public SessionManager()
{
_clockWatch = new Stopwatch();
_timer = new Timer(1000);
_timer.Elapsed += timerElapsed;//focus on this here
_isWatching = false;
current_time = new DateTime();
CurrentTime = DateTime.Now;
_timer.Start();
}
public void timerElapsed(object sender, ElapsedEventArgs e)
{
CurrentTime = DateTime.Now;
if (CurrentTime.TimeOfDay == TimeSpan.Parse("9:32 AM") && NewDayEvent != null)
{
NewDayEvent(this, new EventArgs());
}
if (isWatching)
{
if (CurrentSession != null)
{
//update the timespent variable of the current timeEntry
if (CurrentSession.currentTimeEntry != null)
{
CurrentSession.currentTimeEntry.TimeSpent = _clockWatch.Elapsed;
calculateTotalTime();
CalculateFilteredTimeSpent();
}
}
}
}
}
順便說一下,我在Debug中運行。 –
CurrentSession值如何?它是否爲空? – Shyju
@Shyju:我已經檢查過isWatching是否真的,它是,但它仍然完全跳過它。它甚至沒有達到if(isWatching)行。如果它沒有達到這一線,爲什麼會更深入? –