user222427
user222427

Reputation:

How to make a List<string> {get;set;} per thread,

I have a class that requires dynamically setting a List. I also call this class 10 or so different times using Threading.

public static List<string> MyList {get;set;}

I'm new to threading, however, as I've been told this is unsafe. The question I have is how do I make an instance of MyList per thread?

An example would be awesome!

Upvotes: 6

Views: 5632

Answers (1)

Jord&#227;o
Jord&#227;o

Reputation: 56507

Use the ThreadStatic attribute.

[ThreadStatic] private static List<string> _myList;

public static List<string> MyList {
  get { return _myList; }
  set { _myList = value; }
}

Also, usually it's better for the containing class to have control over the collection; this would mean no externally-visible setter and a getter that returns either a copy or a read-only collection.

But, this might not have the effect you intend. Each thread will have its own copy of the collection. Maybe what you need is to take a look at locks or rethink your design.

Upvotes: 7

Related Questions