【发布时间】:2016-06-27 18:07:55
【问题描述】:
我启动了一个带有回调函数的计时器。但是在这个回调函数中,我更改/初始化了一个在定时器启动后使用的静态对象。
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);
}
}
当我使用静态变量时,我有一个异常“参数超出范围异常”。我认为问题在于回调函数没有完成她的执行并且对象还没有初始化。
我尝试了这个解决方案,但这不起作用:
// 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);
但是有了这个,它就可以了:
Timer addbobs = new Timer((e) => callbackFunct("arg"), null, 0, 10000);
Thread.Sleep(2000);
Console.WriteLine(listDog[0].name);
我希望我的回调函数在下一条语句之前完成她的执行。 你有解决我的问题的方法吗?
上次编辑:是的,我希望能够将参数传递给 callbackFunct
【问题讨论】:
-
你不应该得到一个空引用异常,你应该得到一个索引超出范围异常。您能告诉我们例外的确切措辞吗?
-
是的,对不起,这是一个“参数超出范围异常”
-
new Timer(callbackFunct, null, 0, 10000);无法编译。您可以发布您实际使用的代码,或者修复您的示例代码以便编译吗? -
您是否只想等待添加第一项?
-
@Quantic 抱歉我改了
标签: c# multithreading timer callback