S3005 — "ThreadStatic" should not be used on non-static fields

Language
C#
Type
Bug
Severity
Major
Tags
unused

Why is this an issue?

When you annotate a field with the ThreadStatic attribute, it is an indication that the value of this field is unique for each thread. But if you don’t mark the field as static, then the ThreadStatic attribute is ignored.

The ThreadStatic attribute should either be removed or replaced with the use of ThreadLocal<T> class, which gives a similar behavior for non-static fields.

How to fix it

Code examples

Noncompliant code example


public class MyClass
{
  [ThreadStatic]  // Noncompliant
  private int count = 0;

  // ...
}

Compliant solution


public class MyClass
{
  private int count = 0;

  // ...
}

or


public class MyClass
{
  private readonly ThreadLocal<int> count = new ThreadLocal<int>();
  public int Count
  {
    get { return count.Value; }
    set { count.Value = value; }
  }
  // ...
}

Resources

Documentation

↑ Back to top