DispatcherTimer在Console中不起作用

时间:2013-10-13 23:22:49

标签: c# timer dispatchertimer

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

您可以在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();
    }
}

2 个答案:

答案 0 :(得分:4)

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

您仍然可以使用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
    }

答案 1 :(得分:1)

DispatcherTimer在UI线程上触发其Tick事件。并且您正在以控制台模式运行代码。我认为这就是答案!