DispatcherTimer停止不停止 [英] DispatcherTimer Stop not stopping
问题描述
更新:我把完整的code仅供参考
我试图用调度方法,而不是Forms.Timer()
我停在方法结束,但它一直在停止前循环多次。出了什么问题?
顺便说一句,我不得不提,怎么做,如果语句中使用的MessageBox.show()计时器内。不知道这是原因还是不行。
私人DispatcherTimer mytimer =新DispatcherTimer();
公共主窗口()
{
的InitializeComponent();
}
无效mytimer_Tick(对象发件人,EventArgs的)
{
如果(mytimer.Interval ==新的时间跨度(0,0,2))
{
mytimer.Stop();
如果(textBox1.Text.Length&其中; = 1)
{
的MessageBox.show(0);
mytimer.Stop();
}
其他
{
//做code
的MessageBox.show(超过0);
mytimer.Stop();
}
}
}
私人无效textBox1_TextChanged(对象发件人,TextChangedEventArgs E)
{
mytimer.Interval =新时间跨度(0,0,2);
mytimer.Tick + =新的EventHandler(mytimer_Tick);
mytimer.Start();
}
每个文本改变时,添加事件处理程序的再次的。所以,如果5个字符的输入, mytimer_Tick
将被调用5次。
要解决这个问题,分配事件处理程序只有一次,例如,在窗口的构造函数:
公共窗口1()
{
的InitializeComponent();
mytimer.Interval =新的时间跨度(0,0,2);
mytimer.Tick + =新的EventHandler(mytimer_Tick);
}
私人无效txtInput_TextChanged(对象发件人,EventArgs的)
{
mytimer.Start();
}
Update: I put the complete code for reference
I'm trying to use Dispatcher method instead of Forms.Timer()
I have stop at the end of the method, but it kept looping multiple times before stopping. What went wrong?
By the way, I have to mention that I do use a MessageBox.Show() inside the timer if statement. Don't know if this is the cause or not.
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();
}
Every time the text is changed, you add the event handler again. So, if 5 characters are typed, mytimer_Tick
will be called 5 times.
To fix this, assign the event handler only once, for example, in the Window constructor:
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();
}
这篇关于DispatcherTimer停止不停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!