显示消息框时,计时器继续

时间:2018-04-15 17:20:18

标签: c# wpf

我希望即使显示一个消息框,也允许计时器继续倒计时。当计时器达到30秒和零秒时,将显示消息框。但是,当前计时器停止,直到用户关闭消息框。我目前的代码如下;

_Time = TimeSpan.FromSeconds(60);

_Timer = new DispatcherTimer(new TimeSpan(0, 0, 1), DispatcherPriority.Normal, delegate
    {
        O2_Timer.Text = _Time.ToString("c");
        if (_Time == TimeSpan.FromSeconds(30))
        {
            MessageBox.Show("timer is at 30 seconds");
        }
        if (_Time == TimeSpan.Zero)
        {
            _Timer.Stop();
            MessageBox.Show("timer done");
            Sub_Depth.Text = null;
        }
        _Time = _Time.Add(TimeSpan.FromSeconds(-1));
    }, Application.Current.Dispatcher);

    _Timer.Start();

提前谢谢。

1 个答案:

答案 0 :(得分:0)

我认为最有效的方法是创建一个新线程并调用它, Messagebox是阻塞的,因为它在同一个线程上,如果你将创建并启动一个新线程,它将起作用

_Time = TimeSpan.FromSeconds(60);
 //Creating a new thread
 Thread newMessage = new Thread(runThread);     

_Timer = new DispatcherTimer(new TimeSpan(0, 0, 1),DispatcherPriority.Normal, delegate
  {
    O2_Timer.Text = _Time.ToString("c");
    if (_Time == TimeSpan.FromSeconds(30))
    {
        //Starting the thread
        newMessage.Start();
    }
    if (_Time == TimeSpan.Zero)
    {
        _Timer.Stop();
        MessageBox.Show("timer done");
        Sub_Depth.Text = null;
    }
    _Time = _Time.Add(TimeSpan.FromSeconds(-1));
}, Application.Current.Dispatcher);

_Timer.Start();

private static void runThread(){
    //The thread function
    MessageBox.Show("timer is at 30 seconds");
}