惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
GbyAI
GbyAI
V
Vulnerabilities – Threatpost
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
Recorded Future
Recorded Future
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
博客园 - 司徒正美
Y
Y Combinator Blog
Microsoft Security Blog
Microsoft Security Blog
美团技术团队
博客园 - Franky
Blog — PlanetScale
Blog — PlanetScale
B
Blog RSS Feed
V
Visual Studio Blog
Martin Fowler
Martin Fowler
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园_首页
C
Cybersecurity and Infrastructure Security Agency CISA
博客园 - 叶小钗
AWS News Blog
AWS News Blog
Project Zero
Project Zero
T
Threat Research - Cisco Blogs
V
V2EX
F
Fortinet All Blogs
The GitHub Blog
The GitHub Blog
Latest news
Latest news
N
News and Events Feed by Topic
The Last Watchdog
The Last Watchdog
T
Threatpost
L
Lohrmann on Cybersecurity
小众软件
小众软件
IT之家
IT之家
MongoDB | Blog
MongoDB | Blog
博客园 - 聂微东
Engineering at Meta
Engineering at Meta
爱范儿
爱范儿
Google Online Security Blog
Google Online Security Blog
Forbes - Security
Forbes - Security
Attack and Defense Labs
Attack and Defense Labs
The Register - Security
The Register - Security
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
H
Help Net Security
Security Latest
Security Latest
Recent Announcements
Recent Announcements
C
Check Point Blog
B
Blog
Google DeepMind News
Google DeepMind News
K
Kaspersky official blog
I
InfoQ

博客园 - 南柯之石

用户中心 - 博客园 自引用泛型模式分析 为什么.NET Framework就没有个专门的P/Invoke Library? Which would you perfer? "easy and fast and works well" or "hard and time consuming and error prone" 在ListView的GroupItem头中显示每列的Summary 小例子背后的大道理——用户需求+设计原则+正确应用 =设计方案 GET和POST有什么区别?及为什么网上的多数答案都是错的。 小例子背后的大道理——Adapter模式详解 小例子背后的大道理——从DIP中“倒置”的含义说接口的正确使用 XmlSerializer, DataContractSerializer 和 BinaryFormatter区别与用法分析 使用WPF开发的扫雷游戏,双系统主题复刻版 技术误用带来的技术偏见及所谓的“经验” 从一个UI交互设计师的讲座说开去 NoSQL和MemeryCache的出现意味着传统数据库使用方式的变革吗? 不使用反射进行C#属性的运行时动态访问 一次模块划分的争论及其结局 电子书籍质量保证事件分析 在SQL Server中调用.NET程序集 T-SQL 操作XML示例
一定间隔时间下重复执行一个函数的几个方法
南柯之石 · 2014-03-22 · via 博客园 - 南柯之石

如果有个操作,我们需要过一会儿再做,或者每隔一段时间就要做一次。可以有很多种做法。

独立线程

是的,对.NET Framework本身一知半解的程序员才会使用这种方案。不过,现实中这个方案其实并不少见。

        public static void Repeat(this Action action, TimeSpan interval)
        {
            new Thread(new ThreadStart(() =>
            {
                while(true)
                {
                    Thread.Sleep(interval);
                    action();
                }
            })).Start();
        }

这个方法,相比其他方法,其实还有一个不容小觑的优势:他保证了action只被一个线程调用,如果这个action没有再在别的地方用到的话,那么action就是线程安全的。

Timer类

在.Net Framework中,一共有4个Timer类。Joe Albahari在他的《Threading in C#》中对这4个Timer进行了充分的对比分析。我就不再赘述了。

但是Timer类的缺点也很明显。

l  非线程安全。除了UI上用的两个Timer类,其它的Timer类都不保证它自己一直是被同一个线程执行。当然,这种多线程的执行方式保证了效率与触发事件的时间精度。

l  操作积压。如果一个Timer,100ms触发一次,但是每次却要执行500ms。你可以想象到,你要做的action,本质上就变成了以这样的方式被执行着:

            while(true)

                action();

如果是多线程的Timer,情况会更糟糕,你的这个action会被多个线程同时执行着。多数情况下,我们应该并不希望事情变成这个样子。但是很可惜,Timer类可不会管你的EventHandler的执行时间是多久,他只是到时间就找个线程把你的action执行一次,无论上次action有没有完成。

l  使用不便。想想我们要做什么:“延迟或定时执行一个函数。”,再来看看需要写的代码,我觉得相对于要做的操作而言,过于复杂了。

            Timer timer = new Timer(1000);

            timer.Elapsed += (sender, e) => action();

            timer.Start();

            // 不需要的时候

            timer.Dispose();

再想想,如果你同时要保证线程安全和避免操作积压,又有多少代码要写?于是,Quartz.NET诞生了,以简化这类定时执行操作的代码。

Reactive Extension

事情就可以被简化成:

         Observable.Interval(interval).Subscribe(i => action());

上面的代码的行为与使用Timer类时的行为一样,有操作积压问题。解决方法有很多。这里给出一个我觉得最简单的。

        public static void Repeat(this Action action, TimeSpan interval)
        {
            Observable.Defer(action.ToAsync())
                      .DelaySubscription(interval)
                      .Repeat().Subscribe();
        }

上面的方法,保证了每次action执行之间的时间间隔是一定的。所以不会有action积压的问题出现。