Search code examples
c#uwpdispatchertimer

Dispatch timer won't work


I'm trying to figure out how a dispatch timer works so I can implement it into my program, I followed the exact instructions on a website and looked for answers on stack overflow. People said their problem was fixed but I have very similar code and it wont work...

The error is:

No overload for "timer_Tick" matches delegate "EventHandler<object>"

What can i do?

public MainPage()
{
    this.InitializeComponent();

    DispatcherTimer timer = new DispatcherTimer();
    timer.Interval = TimeSpan.FromSeconds(1);
    timer.Tick += timer_Tick;
    timer.Start();
}

void timer_Tick(EventArgs e)
{
    TimeRefresh();
}

Solution

  • You need to fix the event handler signature. It's missing the sender and the type of the second parameter is just object. (See the documentation.)

    void timer_Tick(object sender, object e)
    {
        TimeRefresh();
    }
    

    You also need to add a using Windows.UI.Xaml; to the top of your class, or instantiate the timer using the full namespace:

    Windows.UI.Xaml.DispatcherTimer timer = new Windows.UI.Xaml.DispatcherTimer();
    

    If anyone stumbles on this and is using WPF, it has it own DispatchTimer. Make sure you're referencing "WindowsBase" (should be there by default). The signature is slightly different.

    void timer_Tick(object sender, EventArgs e)
    {
        TimeRefresh();
    }
    

    The namespace it lives in is different too. Either add using System.Windows.Threading; to the top, or qualify with the full namespace:

    System.Windows.Threading.DispatcherTimer timer
        = new System.Windows.Threading.DispatcherTimer();
    

    If you're using WinForms, you want to use a different timer. Read this for the difference between the WinForms Timer and the WPF DispatchTimer.