DispatcherTimer Stop不停止

3

更新:我提供完整代码以供参考

我正在尝试使用Dispatcher方法,而不是Forms.Timer()

我已经在该方法的末尾停止了,但它在停止之前一直循环多次。出了什么问题?

顺便说一下,我必须提到,在计时器if语句中使用了MessageBox.Show()。不知道这是否是原因。

    private DispatcherTimer mytimer = new DispatcherTimer();

    public MainWindow()
    {
        InitializeComponent();            
    }

    void  mytimer_Tick(object sender, EventArgs e)
    {            
        if (mytimer.Interval == new TimeSpan(0,0,2))
        {
            mytimer.Stop();
            if (textBox1.Text.Length <= 1)
            {
                MessageBox.Show("0");
                mytimer.Stop();
            }
            else
            {
                //do code
                MessageBox.Show("more than 0");
                mytimer.Stop();
            }                
        }

    }

    private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
    {
        mytimer.Interval = new TimeSpan(0, 0, 2);
        mytimer.Tick += new EventHandler(mytimer_Tick);                
        mytimer.Start();        
    }

顺便说一下,在 timer.Start() 之前订阅 Tick ,并在构造函数中执行。 - sll
1个回答

7
每次更改文本时,您都需要再次添加事件处理程序。因此,如果输入5个字符,则会调用mytimer_Tick 5次。
为了解决这个问题,只需一次分配事件处理程序,例如在窗口构造函数中:
public Window1() 
{ 
    InitializeComponent(); 

    mytimer.Interval = new TimeSpan(0,0,2); 
    mytimer.Tick += new EventHandler(mytimer_Tick); 
} 

private void txtInput_TextChanged(object sender, EventArgs e) 
{ 
    mytimer.Start(); 
} 

你说得对!我简直不敢相信我没看到那个。我想我需要休息一下。谢谢! - Corbee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接