0

I have a DispatcherTimer with a Tick event that is stopped after interval. I stop the DispatcherTimer after amount of time in the tick event like this(using 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();
        }
    }

I want to write a method (MyMethod) (from another class that has a logger mechanism) that print a starting message, starting the dispatcher timer, and when the Dispatcher timer is stopped the method needs to print an ending message, like this:

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");           
    }

My problem with this method is that it prints the ending message before the _dispatcherTimer is stopped. and I tried to use SpinWait or Thread.Sleep, but it didn't work for me.

KaliTheGreat
  • 579
  • 6
  • 17

1 Answers1

0

If you want to wait x seconds, you can delay a Task. Example from MSDN:

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