如何等待直到DispatcherTimer停止?

时间:2018-07-10 07:05:04

标签: c# .net dispatchertimer

我有一个DispatcherTimer,它带有一个Tick事件,该事件在间隔之后停止。 在像这样的滴答事件中经过一段时间后,我停止了DispatcherTimer(使用StopWatch):

private void DispatcherTimerTick(object sender, EventArgs e)
    {
        var timeElapsed = _stopwatchTotalProgress.Elapsed;
        if (timeElapsed < selectedBeverage.PreperationTime)
            //do something
        else
        {
            //do somthing
            _dispatcherTimerUpdateProgress.Stop();
            _stopwatchTotalProgress.Reset();
        }
    }

我想编写一个方法(MyMethod)(来自另一个具有记录器机制的类),该方法打印开始消息,启动调度程序计时器,并且当Dispatcher计时器停止时,该方法需要打印一个结束消息,如下所示:

public void MyMethod()
    {
        _logger.notifyMessage("The DispatcherTimer is started");
        _dispatcherTimerUpdateProgress.Start();
        _stopwatchTotalProgress.Start();
        //need to be a kind of waiting until the dispatcher timer is stopped.
        _logger.notifyMessage("The DispatcherTimer is stopped");           
    }

此方法的问题在于,它在_dispatcherTimer停止之前打印结束消息。 并且我尝试使用SpinWait或Thread.Sleep,但对我而言不起作用。

1 个答案:

答案 0 :(得分:0)

如果要等待x秒,则可以延迟任务。 MSDN中的示例:

Stopwatch sw = Stopwatch.StartNew();
var delay = Task.Delay(1000).ContinueWith(_ =>
                           { sw.Stop();
                             return sw.ElapsedMilliseconds; } );
Console.WriteLine("Elapsed milliseconds: {0}", delay.Result);