An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
unlike the system.timer class which runs the callback on the same thread, the System.Threading runs the callback on a thread from the thread pool.
using System;
using System.Threading;
var n = 3; // n seconds
var counter = 0; // non thread safe counter
var locker = new object(); // object to lock on
// timer fire once now
var timer1 = new Timer(
callback: new TimerCallback(TimerProc),
state: "timer1", // state
dueTime: 0, // start with no delay
period: Timeout.Infinite // only once
);
// timer fire only once after n seconds
var timer2 = new Timer(
callback: new TimerCallback(TimerProc),
state: "timer2", // state
dueTime: n * 1000, // start in 1 second
period: Timeout.Infinite // only once
);
// timer fire only once after n seconds
var timer3 = new Timer(
callback: new TimerCallback(TimerProc),
state: "timer3", // state
dueTime: n * 1000, // start in 1 seconds
period: 10 * 1000 // repeat every 10 seconds
);
// delay main thread until timer thread complete
Thread.Sl eep(35000);
timer3.Dispose(); // cancel running timer
Console.WriteLine("all done");
void TimerProc(object? state)
{
var t = 0;
lock (locker)
{
// simulate non threadsafe work
var a = counter;
Thread.Sl eep(1000);
counter = a + 1;
t = counter;
}
Console.WriteLine($"{state}: counter: {t} thread: {Thread.CurrentThread.ManagedThreadId}");
}
note: because thread2 and thread3 start at the same time, its undefined which runs and completes first.