C# timer callback
Solution 1
The System.Threading.TimerCallback
delegate allows you to pass a context object to the callback method. You can use this context object to pass the state that you need in the callback handler. This way it wont matter what thread you are called back on, as you won't need to use ThreadStatic.
The state
argument that you pass to the Timer
constructor will be passed to the callback method.
Solution 2
To answer your question, no there is no such thing as a "reserved" thread for the TimerCallback. The event is scheduled on a ThreadPool and there is no guarantee that the next tick will happen on the same thread, even tho it is possible.
A simple test illustrates this:
myTimer = new System.Threading.Timer(timer_Elapsed, null, 0, Timeout.Infinite);
static void timer_Elapsed(object state)
{
Thread.Sleep(100);
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
myTimer.Change(100, Timeout.Infinite);
}
And the results:
Thomas
Updated on June 06, 2022Comments
-
Thomas almost 2 years
if I set a timer like this:
var MyTimer = new Timer(RunTask, AutoEvent, 1000, 2000);
is it guaranteed that RunTask will always be run on the same thread?
all my tests seem to indicate that it is the case, but is it a guarantee or luck?
this is quite important since I need to store variables that persist call to call and I'm currently using the [ThreadStatic] attribute on them.
I know that if the call back is holding the thread longer than the timer delay, the timer will do another callback on another thread; so I narrow the question to the case where there are no parallel runs (I block teh timer during the callback).
-
Oliver over 6 yearsFrom the docs: The method specified for callback should be reentrant, because it is called on ThreadPool threads. The method can be executed simultaneously on two thread pool threads if the timer interval is less than the time required to execute the method, or if all thread pool threads are in use and the method is queued multiple times. msdn.microsoft.com/en-us/library/ms149618(v=vs.110).aspx
-
Thomas over 6 yearsI added some clarification; if there is no thread guarantee, how can one keep context from one call to another?
-
-
Thomas over 6 yearsthat's why I was curious, I did the same on my system (Windows Server 2016 in a VM on a Mac) and as long as the callback is finished in time, it would always pick the same thread, but I couldn't understand how it could be guaranteed. Anyhow, thanks for putting an example together.