C# 调度员停止不停止
更新:我把完整的代码作为参考 我尝试使用Dispatcher方法而不是Forms.Timer() 我已经在方法的末尾停止了,但它在停止之前一直循环多次。出了什么问题 顺便说一下,我必须提到,我确实在timer if语句中使用了MessageBox.Show()。不知道这是不是原因C# 调度员停止不停止,c#,.net,wpf,C#,.net,Wpf,更新:我把完整的代码作为参考 我尝试使用Dispatcher方法而不是Forms.Timer() 我已经在方法的末尾停止了,但它在停止之前一直循环多次。出了什么问题 顺便说一下,我必须提到,我确实在timer if语句中使用了MessageBox.Show()。不知道这是不是原因 private DispatcherTimer mytimer = new DispatcherTimer(); public MainWindow() { Initializ
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();
}
private dispatchermer mytimer=new dispatchermer();
公共主窗口()
{
初始化组件();
}
void mytimer_Tick(对象发送方,事件参数e)
{
如果(mytimer.Interval==新的时间跨度(0,0,2))
{
mytimer.Stop();
如果每次更改文本时(textBox1.Text.Length,您将再次添加事件处理程序。因此,如果键入5个字符,mytimer\u 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();
}
顺便说一句,订阅timer.Start()
之前的Tick
,然后在构造函数onceYour right中完成!我真不敢相信我没有看到。我想我需要一些睡眠。谢谢!