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.
The problem is that the signature of your
test()
method:doesn't match the required signature for
TimerCallback
:That means you can't create a
TimerCallback
directly from thetest
method. The simplest thing to do is to change the signature of yourtest
method:Or you could use a lambda expression in your constructor call:
Note that to follow .NET naming conventions, your method name should start with a capital letter, e.g.
Test
rather thantest
.TimerCallback
delegate (first argument of theTimer
constructor you use) takes one argument (state) of typeobject
.All you have to do it to add parameter to the
test
methodAnd the issue will be resolved.
write the test method as follows to resolve the exception: