Performing a Periodic Compute-Bound Operation

To perform a periodic compute-bound operation we can
use a timer class.

public Timer(
    TimerCallback callback,
    Object state,
    int dueTime,
    int period
)

Parameters:

callback – A TimerCallback
delegate representing a method to be executed.

state – An object containing information to be used by the callback method, or null reference.

dueTime – The amount of time to delay before callback is invoked, in milliseconds. Specify Timeout.Infinite to
prevent the timer from starting. Specify zero (0) to start the timer
immediately.

period  – The
time interval between invocations of callback, in milliseconds. Specify Timeout .Infinite to
disable periodic signaling.

When
a long-running operation is running the timer can go off so this could cause multiple
threads pools threads to be executed:

static void Main(string[]
args)

{

System.Threading.Timer
s_global = null;

using
(s_global = new System.Threading.Timer(state =>

{

Console.WriteLine(state);

s_global.Change(200,
System.Threading.Timeout.Infinite);

}

, “state”,
0, System.Threading.Timeout.Infinite))

{

Console.ReadKey();

}

}