I launch a timer with a callback function. But in this callback function I change/initialize a static object which is used after the launch of timer.
public class TimerExecute
{
// Assume that the "Dog" class exist with attribute Name initialized in the constructor
public static List<Dog> listDog = new List<Dog>();
public void callbackFunct(String param) {
// code...
listDog.Add(new Dog("Bob"));
// code...
}
public void Main() {
// add dogs Bob each 10sec
Timer addbobs = new Timer((e) => callbackFunct("arg"), null, 0, 10000);
// return argumentoutofrange exception
Console.WriteLine(listDog[0].name);
}
}
When I use the static var, I have an Exception “argument out of range exception”. I think the problem is that callback function doesn’t finished her execution and the object is not yet initialize.
I tried this solution but this doesn't work :
// add dogs Bob each 10sec
Timer addbobs = new Timer((e) => callbackFunct("arg"), null, 0, 10000);
WaitHandle h = new AutoResetEvent(false);
addbobs.Dispose(h);
Console.WriteLine(listDog[0].name);
But with this, it works :
Timer addbobs = new Timer((e) => callbackFunct("arg"), null, 0, 10000);
Thread.Sleep(2000);
Console.WriteLine(listDog[0].name);
I want that my callback function finishes her execution before the next statement. Do you have a solution for my problem ?
Last Edit : Yes I want to be able to pass parameters to callbackFunct