我告诉计时器在构造函数中启动。它启动,但是当它到达它的Timer.Elapsed事件时,它只运行方法中的第一个if语句。我已经检查了isWatching是否是真的,但它仍然完全跳过它。它甚至没有到达if(isWatching)线。
代码:
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();
}
}
}
}
}发布于 2015-12-25 15:43:49
调用TimeSpan.Parse()时没有使用正确的格式。做你想做的事情的正确方法是:
TimeSpan.Parse("9:32")当前的代码片段引发一个System.FormatException。
A first chance exception of type 'System.FormatException' occurred in mscorlib.dll然而,对于你想要达到的目标,每天在特定的时间触发一次动作,上面的方法可能不是最好的,因为成功的机会很小。计时器每1000毫秒运行一次,然后返回包含毫秒的当前时间。因此,计时器经过事件可以在9:32.0001被调用,并且可能永远不会通过该条件。另一种更好的选择可能是:
if (CurrentTime.TimeOfDay >= TimeSpan.Parse("9:32") && NewDayEvent != null)在这段时间过去之后,这将触发不止一次,因此您可以添加一个标记来跟踪处理最后一个事件的日期。
或者,您也可以查看ScheduleAction中的.NET 4.5或一些解决方案这里。
https://stackoverflow.com/questions/34463849
复制相似问题