Skip to content

Gendarme.Rules.Concurrency.DoNotUseThreadStaticWithInstanceFieldsRule(2.10)

Sebastien Pouliot edited this page Feb 9, 2011 · 3 revisions

DoNotUseThreadStaticWithInstanceFieldsRule

Assembly: Gendarme.Rules.Concurrency
Version: 2.10

Description

This rule will fire if an instance field is decorated with a ThreadStatic attribute. This is an error because the attribute will only work with static fields.

Examples

Bad example:

// the field isn't static so this will do nothing
[ThreadStatic]
private List<object> items;
public void Add (object item)
{
    // If the field was thread safe this would ensure that each thread had
    // its own copy of the list.
    if (items == null) {
        items = new List<object> ();
    }
    items.Add (item);
}

Good example:

private List<object> items = new List<object> ();
private object mutex = new object ();
// Typically some form of locking such as the code below is used to
// serialize access to instance fields. However you can also use
// Threading.Thread.Thread::AllocateNamedDataSlot or AllocateDataSlot.
public void Add (object item)
{
    lock (mutex) {
        items.Add (item);
    }
}

Notes

  • This rule is available since Gendarme 2.6
Clone this wiki locally