Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One timer, many method calls or many timers, one method call?

I'm developing an application for WinCE 5.0 on .NET CF 2.0.

I was wondering what other people see as the best solution in the following two cases:

Assume that i have 10 methods that i need to run every 50mS.

Solution 1:

Create one System.Threading.Timer that runs every 50mS and then in this callback run the above mentioned 10 methods.

Solution 2:

Create 10 System.Threading.Timer that runs every 50mS and then in each of their callbacks call one of the above methods.

Which solution do you think is best? Some of the methods are cpu intensive, others are not.

like image 888
user653258 Avatar asked Mar 10 '11 09:03

user653258


3 Answers

Using multiple timers makes the calls independent. That matters most with respect to exceptions. Do you want the other methods to proceed if #2 throws? Are the methods otherwise dependent on each other?

With multiple timers on a multi-core you will profit by executing on the ThreadPool.

Under Win-CE you are probably running on a single core, making part of this reasoning academic.

like image 170
Henk Holterman Avatar answered Nov 19 '22 03:11

Henk Holterman


I don't think I'd use a Timer at all. A Timer is going to spawn a thread when it fires, which a) takes more time and b) allows for reentrancy, meaning you could be running your methods, especially if they take a while, simultaneously.

I'd spawn a single thread at startup (you define what that means - app startup, some object creation, etc) that does all the reads sequentially, does a Sleep call and then repeats.

Something along these lines:

private void Startup()
{
    new Thread(WorkerProc) { IsBackground = true }
    .Start();
}

private void WorkerProc()
{
    int pollPeriod = 50;

    while (true)
    {
        var et = Environment.TickCount;

        // call your methods

        et = Environment.TickCount - et;
        var sleep = pollPeriod - et;
        if (sleep < 0) sleep = 0; // always yield
        Thread.Sleep(sleep);
    }
}
like image 45
ctacke Avatar answered Nov 19 '22 01:11

ctacke


It boils down to how accurate those methods needs to be. Calling each method in sequence (using the same timer) will not run all methods every 50ms, since each method takes time to complete.

If all methods must run every 50s: use different timers; otherwise use the same timer.

like image 1
jgauffin Avatar answered Nov 19 '22 02:11

jgauffin