gpt4 book ai didi

c# - DispatcherTimer 在控制台中不起作用

转载 作者:行者123 更新时间:2023-12-01 19:13:23 24 4
gpt4 key购买 nike

我很好奇为什么调度程序计时器在控制台模式下不起作用。我创建了一个简单的警报,当计时器达到限制时它会执行一些操作。

您可以在 UnitTest 或控制台模式下使用调度程序计时器吗?当我在表单中运行 DailyAlarm 时,它就可以工作。

这是我调用计时器的代码

[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();
}
}

最佳答案

默认情况下,控制台和单元测试环境没有调度程序来运行调度程序计时器。

您仍然可以使用 Dispatcher.CurrentDispatcher 创建 Dispatcher 来运行您的代码。

http://consultingblogs.emc.com/crispinparker/archive/2010/10/22/unit-testing-a-wpf-dispatchertimer-method.aspx 有一个使用示例

使用此 DispatcherHelper,您可以使用以下方法测试您的代码:

    [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
}

关于c# - DispatcherTimer 在控制台中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19351473/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com