c# 计时器自然是多线程的吗? [英] Are c# timers naturally multithreaded?

查看:16
本文介绍了c# 计时器自然是多线程的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个系统计时器分别在 10 秒和 20 秒触发事件,对事件函数的调用是否是多线程的?在下面的场景中,我的计时器分别以 10 秒和 12 秒的间隔触发事件.函数My10sEvent"预计将首先被调用.如果是一个慢函数,需要 8 秒才能运行,它会阻塞另一个事件(tmr12s),还是第二个事件会在 12s 时准时触发?

If I have two system timers firing events at 10 and 20s respectively, are the calls to the event functions multithreaded? In the scenario below, I have timers that fire events at 10 and 12s intervals respectively. The function 'My10sEvent' is expected to be called first. If it is a slow function that takes 8 seconds to run, will it block the other event (tmr12s), or will the second event fire on time at 12s?

System.Timers.Timer tmr10s = new System.Timers.Timer(10000.0);
tmr10s.Enabled = true;
tmr10s.Elapsed += new ElapsedEventHandler(My10sEvent);

System.Timers.Timer tmr12s = new System.Timers.Timer(12000.0);
tmr12s.Enabled = true;
tmr12s.Elapsed += new ElapsedEventHandler(My12sEvent);

Thread.Sleep(System.Threading.Timeout.Infinite); //sleep indefinitely to let the above events fire

推荐答案

CLR 使用专用线程来跟踪活动的 System.Timers.Timer 和 System.Threading.Timer 计时器.Elapsed 事件在从线程池中拉出的另一个线程上引发.

The CLR uses a dedicated thread to keep track of active System.Timers.Timer and System.Threading.Timer timers. The Elapsed event is raised on another thread pulled from the threadpool.

所以是的,它们一直在滴答作响,而不会相互影响.您必须非常小心,您的 Elapsed 事件处理程序很有可能在它仍在执行时再次被调用.当它花费的时间超过间隔时会发生这种情况.或者更糟的是,当机器负载很重或者您有很多活动线程池线程时.如果您的事件处理程序不是线程安全的,这可能会导致很难诊断故障.几乎从来没有.将计时器的 AutoReset 属性设置为 false 是避免此问题的简单方法.

So yes, they keep ticking without affecting each other. You have to be very careful, it is quite possible for your Elapsed event handler to be called again while it is still executing. Which happens when it takes longer than the interval. Or worse, when the machine is heavily loaded or you have a lot of active threadpool threads. This can cause very hard to diagnose failure if your event handler isn't thread-safe. It almost never is. Setting the timer's AutoReset property to false is a simple way to avoid this problem.

这篇关于c# 计时器自然是多线程的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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