I'm curious as to why dispatcher timer doesn't work in console mode. I created a simple alarm that does something when the timer reaches it's limit.
Can you use dispatcher timer with UnitTest or in Console mode? DailyAlarm works when I run it in a form.
Here's my code to call the timer
[TestClass]
public class UnitTest1
{
bool runTest = true;
[TestMethod]
public void TestDailyAlarm()
{
DateTime alarmTime = new DateTime();
alarmTime= DateTime.Now;
alarmTime = alarmTime.AddSeconds(5);
// MessageBox.Show(alarmTime.ToString());
DailyAlarm alarm = new DailyAlarm(alarmTime);
alarm.DailyAlarmEvent += alarm_DailyAlarmEvent;
alarm.Start();
while (runTest)
{
System.Threading.Thread.Sleep(1000);
}
}
void alarm_DailyAlarmEvent(EventArgs e)
{
MessageBox.Show("Alarm On");
runTest = false;
}
}
Here's my timer code
public class DailyAlarm
{
#region Timer
DispatcherTimer timer;
#endregion
#region AlarmTime
DateTime _alarmTime;
#endregion
#region Event
public delegate void DailyAlarmHandler(EventArgs e);
public event DailyAlarmHandler DailyAlarmEvent;
#endregion
public DailyAlarm(System.DateTime alarmTime)
{
if (alarmTime < DateTime.Now)
{
alarmTime = alarmTime.AddDays(1);
}
_alarmTime = alarmTime;
TimeSpan timeRemaining = alarmTime.Subtract(DateTime.Now);
timer = new DispatcherTimer();
timer.Tick += AlarmEvent;
timer.Interval = timeRemaining;
}
public void Start()
{
timer.Start();
}
private void AlarmEvent(object sender, EventArgs e)
{
DailyAlarmEvent(null);
// Calculate next Alarm
_alarmTime = _alarmTime.AddDays(1);
TimeSpan timeRemaining = _alarmTime.Subtract(DateTime.Now);
Utilities.DispatcherTimer_ChangeInterval(ref timer, timeRemaining);
}
public void Stop()
{
if (timer != null)
timer.Stop();
}
}