我想做的事。我想 SomeMethod 将被定期调用。因此,我想在后台线程方法主体通过后从后台线程启动计时器。_timer.Start()
被调用,但 TickHandler 没有;
代码:
using Timer = System.Windows.Forms.Timer;
class TestTimer
{
private Timer _timer;
private Thread _thread;
public TestTimer()
{
// create and initializing timer. but not started!
_timer = new Timer();
_timer.Tick += TickHandler;
_timer.Interval = 60000; // 1 minute
// create and start new thread
_thread = new Thread(SomeMethod);
_thread.Start();
}
private void TickHandler(object sender, EventArgs e)
{
// stop timer
_timer.stop();
//some handling
// run background thread again
_thread = new Thread(SomeMethod);
_thread.Start();
}
private void SomeMethod()
{
// some operations
// start timer!
TimerStart();
}
private void TimerStart()
{
_timer.Start();
}
}
通过猴子方法,我发现如果像这样添加代表
internal delegate void TimerDelegate();
并替换字符串
TimerStart();
和
Application.Current.Dispatcher.Invoke(new TimerDelegate(TimerStart), null);
一切正常。有人可以解释我的诀窍是什么吗?