ThreadStatic Instance Field

ID

csharp.thread_static_instance_field

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

CSharp

Tags

concurrency, reliability

Description

Reports fields decorated with the [ThreadStatic] attribute that are not declared static. The attribute is silently ignored on instance fields, so the value is shared between threads even though the author clearly intended thread-local storage.

Rationale

[ThreadStatic] requests that the runtime allocate one slot per thread for the decorated field. The CLR only honours that request for static fields; on instance fields the attribute is a no-op, so any thread that reads or writes the field sees the same shared value as every other thread. The bug usually surfaces as data corruption under load, far away from the field declaration.

public class Counter
{
    [ThreadStatic]
    private int badCounter;             // FLAW — attribute ignored, shared between threads

    [ThreadStatic]
    private static int goodCounter;     // OK — thread-local

    private static int sharedCounter;   // OK — explicit shared state, no attribute
}

Remediation

Either mark the field static so the runtime honours the [ThreadStatic] attribute, or remove the attribute and use ThreadLocal<T> (which works on instance fields and supports a value factory) when per-instance, per-thread storage is required.