2

I want to use C# Timer in DLL application

DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
TimeSpan interval = TimeSpan.FromMinutes(5);
dispatcherTimer.Interval = interval;
dispatcherTimer.Start();

but the problem is that is never triggered. Method dispatcherTimer_Tick is never triggered even if time is 5 minutes. There is no error nothing.

Any idea why? I am using .net 4.0

mbrc
  • 3,523
  • 13
  • 40
  • 64

2 Answers2

3

Use System.Timers.Timer instead,

    System.Timers.Timer myTimer = new System.Timers.Timer(5 * 60 * 1000);            
    myTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);            
    myTimer.Enabled = true;
    myTimer.Start();

This works in all the application type, whether app is web, console, WPF etc and you do not need to worry about the environment or application it is been used.

Deepak Bhatia
  • 6,230
  • 2
  • 24
  • 58
1

For DispatcherTimer to work, your app must be running a message pump. If it's a console application or web application, there isn't a message pump, so DispatcherTimer can't work.

DispatcherTimer is designed for use in WPF applications. If you need a timer in an application with no UI, use System.Threading.Timer or System.Timers.Timer.

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758