rspec/rules/S3005/csharp/rule.adoc

53 lines
1.0 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
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.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
----
public class MyClass
{
[ThreadStatic] // Noncompliant
private int count = 0;
// ...
}
----
2021-04-28 16:49:39 +02:00
== 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; }
}
// ...
}
----
ifdef::rspecator-view[]
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::rspecator-view[]