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

做这样的事情是安全的:
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();
}

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

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...