DispatcherTimer 在控制台中不起作用 [英] DispatcherTimer doesn't work in Console
问题描述
我很好奇为什么调度程序计时器在控制台模式下不起作用.我创建了一个简单的闹钟,当计时器达到限制时会做一些事情.
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.
您可以在 UnitTest 或控制台模式下使用调度程序计时器吗?DailyAlarm 在我以表单形式运行时工作.
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;
}
}
这是我的计时器代码
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();
}
}
推荐答案
控制台和单元测试环境默认没有调度器来运行调度器计时器.
The console and unit test environment by default don't have a dispatcher to run your dispatcher timer.
您仍然可以使用 Dispatcher.CurrentDispatcher 创建一个 Dispatcher 来运行您的代码.
You can still use Dispatcher.CurrentDispatcher to create a Dispatcher to run your code.
使用此 DispatcherHelper,您可以测试您的代码:
With this DispatcherHelper you can test your code with:
[TestMethod]
public void TestMethod1()
{
Action test = () =>
{
var dailyAlarm = new DailyAlarm(DateTime.Now.AddSeconds(5.0));
dailyAlarm.DailyAlarmEvent += dailyAlarm_DailyAlarmEvent;
dailyAlarm.Start();
};
DispatcherHelper.ExecuteOnDispatcherThread(test, 20);
}
void dailyAlarm_DailyAlarmEvent(EventArgs e)
{
// event invoked when DispatcherTimer expires
}
这篇关于DispatcherTimer 在控制台中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!