计时器已停止,但显然无法结束回调循环

问题描述 投票:0回答:1

我有这个计时器每 1 秒读取一次文本框值。一旦系统读取该值,计时器就会停止并更改标签值。离开该计时器后,它应该继续处理我的其他逻辑。但显然它卡在了timer_tick的循环中。

我尝试用断点来追踪问题。请注意,程序按下回车键后; ,它进入回调函数并陷入循环。

 private void Form1_Load(object sender, EventArgs e)
 {
    if (m_blnReset)
    {
     this.PickNoteTimer();
    }

    //other logics
 }

 private void PickNoteTimer()
 {
    this.ReadPickNoteTimer = new System.Windows.Forms.Timer { Interval = 1000 };
    this.ReadPickNoteTimer.Tick += new EventHandler(PickNoteTimer_Tick);
    this.ReadPickNoteTimer.Start();
 }

 private void PickNoteTimer_Tick(object sender, EventArgs e)
 {
    if (!string.IsNullOrEmpty(txtBoxPicknoteNumber.Text))
    {
      this.m_Picknote = txtBoxPicknoteNumber.Text.ToString();
      this.GetPickNoteDetails();

      if (this.ReadPickNoteTimer.Enabled)
         this.ReadPickNoteTimer.Stop();
      else
         return;
    }
}

private void GetPickNoteDetails()
{
   this.ReadPickNoteTimer.Stop();

   //logics to update value on label

 }
}
c# winforms timer
1个回答
0
投票

一个可能的问题是您在

PickNoteTimer_Tick
方法和
GetPickNoteDetails
方法中停止计时器。您应该从
this.ReadPickNoteTimer.Stop();
方法中删除
GetPickNoteDetails
调用,因为那里不需要它。当满足条件
PickNoteTimer_Tick
时,应在
if (!string.IsNullOrEmpty(txtBoxPicknoteNumber.Text))
方法中停止计时器。

这是更新后的代码:

private void PickNoteTimer_Tick(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(txtBoxPicknoteNumber.Text))
    {
        this.m_Picknote = txtBoxPicknoteNumber.Text;
        this.GetPickNoteDetails();

        if (this.ReadPickNoteTimer.Enabled)
            this.ReadPickNoteTimer.Stop();
    }
}

private void GetPickNoteDetails()
{
    // Logics to update value on label
    // You don't need to stop the timer here
}

如果您仍然面临计时器卡住的问题,则您的应用程序中可能还有其他一些因素导致了该问题。

© www.soinside.com 2019 - 2024. All rights reserved.