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

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

问题描述

如果我有两个分别在10s和20s触发事件的系统计时器,那么对事件函数的调用是否是多线程的?在以下情况下,我有分别以10s和12s为间隔触发事件的计时器.预计将首先调用函数"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天全站免登陆