开发者

Executing a task via a thread on an interval a certain number of times

I don't have a great deal of experience with threads. I'm using .NET 4 and would like to use the .NET 4 threading features to solve this. Here is what I want to do.

I have a class with two methods, 'A' and 'B'. I want 'A' to call 'B' some number of times (like 100) every some number of milliseconds (like 3000). I want to record the average execution time of method 'B' when it's done executing its 100 (or whatever) times. The class will have some private properties to keep track of the total elapsed execution time of 'B' in order to calculate an average.

I'm not sure if method 'A' should call 'B' via a System.Timers.Timer thread (where the interval can be set开发者_运维问答, but not the number of times) or if there is a better (.NET 4) way of doing this.

Thanks very much.


In reading over your question, I think the root question you have is about safely kicking off a set of events and timing their execution in a thread-safe manner. In your example, you are running 100 iterations every 3000ms. That means that at most each iteration should only take 30ms. Unfortunately, the System.Timers.Timer (which is System.Threading.Timer with a wrapper around it) is not that precise. Expect a precision of 10ms at best and possibly a lot worse. In order to get the 1ms precision you really need, you are going to need to tap into the native interop. Here is a quote I found on this:

The precision of multithreaded timers depends on the operating system, and is typically in the 10–20 ms region. If you need greater precision, you can use native interop and call the Windows multimedia timer. This has precision down to 1 ms and it is defined in winmm.dll. First call timeBeginPeriod to inform the operating system that you need high timing precision, and then call timeSetEvent to start a multimedia timer. When you’re done, call timeKillEvent to stop the timer and timeEndPeriod to inform the OS that you no longer need high timing precision. You can find complete examples on the Internet that use the multimedia timer by searching for the keywords dllimport winmm.dll timesetevent

-Joseph Albahari ( http://www.albahari.com/threading/part3.aspx )

If you follow his advice, you should get the precision you need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜