Question

Does anyone have any insight into the implementation of

SystemThreading.Thread.CurrentThread.ManagedThreadId

like if it's doing kernel roundtrips or not? I'm specifically wondering if calling it repeatedly from a multitude of threads is better than reading the value once, store it in thread local storage and then use that value henceforth instead, like

ThreadLocal<int> ThreadId = new ThreadLocal<int>(() =>
    Thread.CurrentThread.ManagedThreadId);
...
Tracer.Add("Thread:" + ThreadId.Value);

I'm about to measure both variants today, but thought it'd be interesting to hear any thoughts (or prejudice :)) beforehand.

Was it helpful?

Solution

CurrentThread and ManagedThreadId are both internall-call properties, so that value retreival is handled by framework itself. Since they are properties, and not methods, it is reasonable to assume that they can be accessed quickly and storing them is not necessary, unless you get them in a loop with lots of iterations.

public extern int ManagedThreadId
{
    [__DynamicallyInvokable, ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), SecuritySafeCritical]
    [MethodImpl(MethodImplOptions.InternalCall)]
    get;
}

If you care about using this property for logging, we can take a look how popular logging frameworks, like NLog, use it. Turns out, it does not cache it, and uses it directly:

namespace NLog.LayoutRenderers
{
    public class ThreadIdLayoutRenderer : LayoutRenderer
    {
        protected override void Append(StringBuilder builder, LogEventInfo logEvent)
        {
            builder.Append(Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture));
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top