加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在自己的匿名Tick事件处理程序中停止DispatcherTimer

发布时间:2020-12-15 04:06:13 所属栏目:百科 来源:网络整理
导读:做这样的事情是安全的: private void MyFunction(){ DispatcherTimer timer = new DispatcherTimer(); timer.Interval = new TimeSpan(0,1); timer.Tick += (object sender,object e) = { timer.Stop(); // Some code here }; timer.Start();} 解决方法 Mat
做这样的事情是安全的:
private void MyFunction()
{
    DispatcherTimer timer = new DispatcherTimer();
    timer.Interval = new TimeSpan(0,1);
    timer.Tick += (object sender,object e) =>
    {
        timer.Stop();
        // Some code here
    };
    timer.Start();
}

解决方法

Matt提出了一种观点,即你附加匿名方法的方式是没有简单的方法来分离它.以下是可用于在必要时分离的一般模式.
private void MyFunction()
{
    DispatcherTimer timer = new DispatcherTimer();
    timer.Interval = new TimeSpan(0,1);
    EventHandler eh = null;
    eh = (object sender,object e) =>
    {
        timer.Tick -= eh;
        timer.Stop();
        // Some code here
    };

    timer.Tick += eh;
    timer.Start();
}

但是在这种特定情况下,原始代码的工作方式没有任何问题,因为定时器一旦停止就会变为可收集状态.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读