0

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();
}
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
mateos
  • 1,405
  • 1
  • 17
  • 26

2 Answers2

5

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.

Community
  • 1
  • 1
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
3

You have to specify the source of event.

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

And the event registration should be like the following:

timer.Tick += new EventHandler(timer_Tick);

Here you can read more about events and event handlers

Community
  • 1
  • 1
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88