0

I'm trying to use a DispatcherTimer without WPF. It doesn't, the tick event is not triggered. See code sample below. Is there a way to make it work?

Why am I trying to do it? I am implementing a unit test for a class that hooks in my view model. That class uses the DispatcherTimer.

    static void Main(string[] args)
    {
        DispatcherTimer timer;
        timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromMilliseconds(50);
        timer.Tick += (s, e) => Console.WriteLine("Hello");
        timer.Start();
        Console.Read();
    }
Johannes Schacht
  • 930
  • 1
  • 11
  • 28
  • 1
    Does this answer your question? [DispatcherTimer doesn't work in Console](https://stackoverflow.com/questions/19351473/dispatchertimer-doesnt-work-in-console) – Kyle Williamson Sep 18 '20 at 18:49
  • Why don't you use a `System.Timers.Timer`? It makes no sense to use a `DispatcherTimer` when there is no dispatcher...If you want to be able unit test your view model, you should mock away the `DispatcherTimer` dependency. – mm8 Sep 18 '20 at 20:31
  • mm8: Yeah, mocking the timer. Thought about that. But my aim was to really test the timer as I had situations (in WPF) where the timer didn't start. I now call the Timer.Tick() function directly from my unit test, which has a similar effect. – Johannes Schacht Sep 18 '20 at 21:49
  • @Kyle: I saw that article already. Thank you. Seems I have use some other strategy in my unit tests. – Johannes Schacht Sep 18 '20 at 21:51

1 Answers1

0

Unfortunately you can't use DispatcherTimer because there is no dispatcher in console apps. Take a look at this question

AdiletB
  • 77
  • 3