更新时间:2023-10-29 11:54:40
您需要解开
的事件
前再次钩住这样的 -
私人无效poc_MouseMove(对象发件人,发送MouseEventArgs E)
{
如果(定时器!= NULL)
{
timer.Tick- = timer_Tick;
}
定时器=新DispatcherTimer();
timer.Interval =新时间跨度(0,0,5);
timer.Tick + =新的EventHandler(timer_Tick);
timer.Start();
}
说明
每当鼠标移动时,将创建DispatcherTimer的新实例,并挂钩Tick事件而不用担心会有脱钩的事件previous实例
什么,你做的是。因此,你看到洪水淹没的消息后,计时器停止所有实例。
此外,你应该解开它,否则previous实例不会被垃圾回收
,因为他们仍然坚决引用
。
I am writing a WPF application. I want to trigger an event once the mouse stops moving.
This is how I tried to do it. I created a timer which counts down to 5 seconds. This timer is "reset" every time the mouse moves. This idea is that the moment the mouse stops moving, the timer stops being reset, and counts down from 5 to zero, and then calls the tick event handler, which displays a message box.
Well, it doesn't work as expected, and it floods me with alert messages. What am I doing wrong?
DispatcherTimer timer;
private void Window_MouseMove(object sender, MouseEventArgs e)
{
timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 5);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
MessageBox.Show("Mouse stopped moving");
}
You need to unhook
the event
before hooking it again like this -
private void poc_MouseMove(object sender, MouseEventArgs e)
{
if (timer != null)
{
timer.Tick-= timer_Tick;
}
timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 5);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
Explanation
What you doing is whenever a mouse moves, you create a new instance of DispatcherTimer and hook Tick event to it without unhooking the event for previous instance
. Hence, you see flooded messages once timer stops for all the instances.
Also, you should unhook it otherwise previous instance won't be garbage collected
since they are still strongly referenced
.