Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

multithreading - Are c# timers naturally multithreaded?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...