6

I'm making a console application that must call a certain method in timed intervals.

I've searched for that and found that the System.Threading.Timer class can achieve such a functionality, but I'm not quite following how to implement it.

I tried this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Timer x = new Timer(test, null, 0, 1000);
            Console.ReadLine();
        }

        public static void test()
        {
            Console.WriteLine("test");
        }
    }
}

But I get an error on the Timer x = new Timer(test, null, 0, 1000); line that says:

The best overloaded method match for System.Threading.Timer.Timer(System.Threading.TimerCallback, object, int, int)' has some invalid arguments

I really don't know how to make this work properly, but if anyone has a link or something that can explain timers for a beginner, I'd be grateful.

Lauren Rutledge
  • 1,195
  • 5
  • 18
  • 27
Rafael Adel
  • 7,673
  • 25
  • 77
  • 118
  • 1
    http://msdn.microsoft.com/en-us/library/system.timers.timer%28v=VS.100%29.aspx not sure he will understand lambda's but Jon's Answer is spot on.. http://msdn.microsoft.com/en-us/library /system.threading.timercallback.aspx http://stackoverflow.com/questions/1416803/system-timers-timer-vs-system-threading-timer – MethodMan Dec 23 '12 at 14:50

3 Answers3

17

The problem is that the signature of your test() method:

public static void test()

doesn't match the required signature for TimerCallback:

public delegate void TimerCallback(
    Object state
)

That means you can't create a TimerCallback directly from the test method. The simplest thing to do is to change the signature of your test method:

public static void test(Object state)

Or you could use a lambda expression in your constructor call:

Timer x = new Timer(state => test(), null, 0, 1000);

Note that to follow .NET naming conventions, your method name should start with a capital letter, e.g. Test rather than test.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • That worked. Thanks. But may you provide me with links that talk about delegates, so i can understand what's it all about ? – Rafael Adel Dec 23 '12 at 14:51
4

TimerCallback delegate (first argument of the Timer constructor you use) takes one argument (state) of type object.

All you have to do it to add parameter to the test method

public static void test(object state)
{
    Console.WriteLine("test");
}

And the issue will be resolved.

Tom
  • 26,212
  • 21
  • 100
  • 111
2

write the test method as follows to resolve the exception:

public static void test(object state)
        {
            Console.WriteLine("test");
        }
Rashedul.Rubel
  • 3,446
  • 25
  • 36