【发布时间】:2021-11-11 06:08:02
【问题描述】:
我有一个 TimerMethod(),它每隔五秒调用一次。到目前为止一切都很好,计时器按预期循环。在定时器里面,我放了一个方法——SomeThreadMethod()。如果我没有在 SomeThreadMethod 中启动线程,一切都很好,计时器继续循环。但是,如果我启动一个线程,计时器将停止循环。该代码有什么问题,如何在循环计时器中使用线程?
public void TimerMethod()
{
Timer timer = new Timer((obj) =>
{
// this point in the code is always reached
System.Diagnostics.Debug.WriteLine("before function call");
SomeThreadMethod();
// this point is never reached, if there is a nested Thread
// inside SomeThreadMethod()
System.Diagnostics.Debug.WriteLine("after function call");
TimerMethod();
timer.Dispose();
},
null, 5000, Timeout.Infinite);
}
public void SomeThreadMethod()
{
// if I use thread here, then the hosting
// TimerMethod stops looping. Why???
// If I do not use a thread here, then
// the timer loops normally
Thread someThread = new Thread(() =>
{
// do something inside thread
});
someThread .Start();
someThread .Join();
}
【问题讨论】:
-
如果您在启动后立即加入线程,那么您不需要线程。
-
为什么要取消计时器并从计时器的滴答处理程序中启动另一个计时器?
-
由于很多原因,您拥有的少量代码显然是错误的,我认为如果您解释一下您要实现的目标,这可能会更容易。
-
这是原始代码的简化版本。 SomeThreadMethod 内部启动了多个线程
-
那么有两个问题:定时器没有按预期使用,这里你可能使用了太多线程。因此,如果您可以发布 minimal reproducible example 并说明您的目标是什么,那就太好了。
标签: c# multithreading timer