如何使用定时器等待? [英] How to use a timer to wait?

查看:36
本文介绍了如何使用定时器等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用计时器来延迟我的方法中的事件,但是我不一定了解如何使用计时器进行等待.

我将计时器设置为 2 秒,但是当我运行此代码时,最后一次调用的运行没有 2 秒的延迟.

Timer timer = new Timer();timer.Tick += new EventHandler(timer_Tick);//每次定时器滴答时,timer_Tick 将被调用timer.Interval = (1000) * (2);//计时器将每秒钟滴答一次timer.Enabled = true;//开启定时器void timer_Tick(对象发送者,EventArgs e){定时器.停止();}private void button1_Click(object sender, EventArgs e){label1.Text = "第一";定时器开始();label1.Text = "第二";}

因此,当我单击按钮时,它立即将 label1 显示为第二个",而不是更改为第一个",等待 2 秒,然后更改为第二个".我在这里阅读了很多关于使用计时器而不是 thread.sleep 的线程,但我似乎无法找到/弄清楚如何实际实现它.

解决方案

timer.Start() 只是启动计时器,但在计时器在后台运行时立即返回.因此,在将标签文本设置为 firstsecond 之间几乎没有停顿.您想要做的是等待计时器滴答作响,然后再次更新标签:

void timer_Tick(object sender, EventArgs e){定时器.停止();label1.Text = "第二";}private void button1_Click(object sender, EventArgs e){label1.Text = "第一";定时器开始();}

顺便说一句.您不应将 timer.Enabled 设置为 true,您已经在使用 timer.Start() 启动计时器.

如评论中所述,您可以将计时器的创建放入一个方法中,如下所示(注意:这是未经测试的):

public void Delayed(int delay, Action action){定时器 timer = new Timer();timer.Interval = 延迟;timer.Tick += (s, e) =>{行动();定时器.停止();};定时器开始();}

然后你可以像这样使用它:

private void button1_Click(object sender, EventArgs e){label1.Text = "第一";Delayed(2000, () => label1.Text = "second");}

Tergiver 的跟进

<块引用>

使用 Delayed 是否包含内存泄漏(引用泄漏)?

订阅事件总是会创建一个双向引用.

在这种情况下 timer.Tick 获取对匿名函数 (lambda) 的引用.该函数提升了一个局部变量 timer,尽管它是一个引用,而不是一个值,并且包含对传入的 Action 委托的引用.该委托将包含对 label1 的引用,它是 Form 的实例成员.那么是否存在从 TimerForm 的循环引用?

我不知道答案,我发现这有点难以推理.因为我不知道,所以除了停止计时器(这是 sendercode> 方法的参数),同时移除事件.

通常 lambda 不会导致垃圾收集问题.在这种情况下,计时器实例仅存在于本地,并且 lambda 中的引用不会阻止垃圾收集来收集实例(另请参见 这个问题).

我实际上使用 .NET Memory Profiler 再次对此进行了测试.定时器对象收集得很好,没有发生泄漏.分析器确实给了我一个警告,说有些情况[...] 没有被正确处理就被垃圾收集了".删除事件处理程序本身(通过保留对它的引用)并没有解决这个问题.将捕获的计时器引用更改为 (Timer)s 也没有改变.

显然有帮助的是在停止计时器后在事件处理程序中调用 timer.Dispose(),但我认为这是否真的有必要.我不认为分析器警告/注释那么重要.

I am trying to delay events in my method by using a timer, however i do not necessarily understand how to use a timer to wait.

I set up my timer to be 2 seconds, but when i run this code the last call runs without a 2 second delay.

Timer timer = new Timer();
timer.Tick += new EventHandler(timer_Tick); // Everytime timer ticks, timer_Tick will be called
timer.Interval = (1000) * (2);              // Timer will tick evert second
timer.Enabled = true;                       // Enable the timer


void timer_Tick(object sender, EventArgs e)
{
    timer.Stop();
}

private void button1_Click(object sender, EventArgs e)
{
    label1.Text = "first";
    timer.Start();
    label1.Text = "second";
}

So when i click my button, it immediately shows label1 as "second", as opposed to changing to "first", waiting 2 seconds, then changing to "second". I have read lots of threads here about using timers instead of thread.sleep, but i cannot seem to find/figure out how to actually implement that.

解决方案

timer.Start() just starts the timer but immediately returns while the timer is running in the background. So between setting the label text to first and to second there is nearly no pause. What you want to do is wait for the timer to tick and only then update the label again:

void timer_Tick(object sender, EventArgs e)
{
    timer.Stop();
    label1.Text = "second";
}

private void button1_Click(object sender, EventArgs e)
{
    label1.Text = "first";
    timer.Start();
}

Btw. you should not set timer.Enabled to true, you are already starting the timer using timer.Start().

As mentioned in the comments, you could put the timer creation into a method, like this (note: this is untested):

public void Delayed(int delay, Action action)
{
    Timer timer = new Timer();
    timer.Interval = delay;
    timer.Tick += (s, e) => {
        action();
        timer.Stop();
    };
    timer.Start();
}

And then you could just use it like this:

private void button1_Click(object sender, EventArgs e)
{
    label1.Text = "first";
    Delayed(2000, () => label1.Text = "second");
}

Tergiver’s follow-up

Does using Delayed contain a memory leak (reference leak)?

Subscribing to an event always creates a two-way reference.

In this case timer.Tick gets a reference to an anonymous function (lambda). That function lifts a local variable timer, though it's a reference, not a value, and contains a reference to the passed in Action delegate. That delegate is going to contain a reference to label1, an instance member of the Form. So is there a circular reference from the Timer to the Form?

I don't know the answer, I'm finding it a bit difficult to reason about. Because I don't know, I would remove the use of the lambda in Delayed, making it a proper method and having it, in addition to stopping the timer (which is the sender parameter of the method), also remove the event.

Usually lambdas do not cause problems for the garbage collection. In this case, the timer instance only exists locally and the reference in the lambda does not prevent the garbage collection to collect the instances (see also this question).

I actually tested this again using the .NET Memory Profiler. The timer objects were collected just fine, and no leaking happened. The profiler did give me a warning that there are instances that "[…] have been garbage collected without being properly disposed" though. Removing the event handler in itself (by keeping a reference to it) did not fix that though. Changing the captured timer reference to (Timer)s did not change that either.

What did help—obviously—was to call a timer.Dispose() in the event handler after stopping the timer, but I’d argue if that is actually necessary. I don’t think the profiler warning/note is that critical.

这篇关于如何使用定时器等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆