Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-3005

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

    XMLWordPrintable

    Details

    • Type: Bug Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Remove the "ThreadStatic" attribute from this definition.
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      C#
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      5min
    • Analysis Scope:
      Main Sources, Test Sources
    • ReSharper:
      ThreadStaticAtInstanceField
    • Quick-fixes:
      Hide

      Remove "ThreadStatic" attribute: removes the attribute. If this is the only one in the attribute list, then the whole attribute list is removed.

      Show
      Remove "ThreadStatic" attribute: removes the attribute. If this is the only one in the attribute list, then the whole attribute list is removed.

      Description

      When a non-static class field is annotated with ThreadStatic, the code seems to show that the field can have different values for different calling threads, but that's not the case, since the ThreadStatic attribute is simply ignored on non-static fields.

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

      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; }
        }
        // ...
      }
      

        Attachments

          Activity

            People

            Assignee:
            Unassigned Unassigned
            Reporter:
            ann.campbell.2 Ann Campbell
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Dates

              Created:
              Updated: