Reputation: 2770
Im awful at multithreadding but ever since I added the following line to my application it seems to crash quite often so Im assuming its not thread safe.
private readonly string[] _foo = Enumerable.Range(1, 1000).Select(i => i.ToString()).ToArray();
What are my options to make this thread safe?
Upvotes: 2
Views: 1018
Reputation: 4629
List<T>
or T[]
--> SynchronizedCollection<T>
(be aware that enumeration is not thread-safe)Dictionary<T>
--> ConcurrentDictionary<T>
Queue<T>
--> ConcurrentQueue<T>
Stack<T>
--> ConcurrentStack<T>
BlockingCollection<T>
for Producer-Consumer scenariosUpvotes: 0
Reputation: 35935
If you are using C# 4 you can use some already built-in collections. They are faster than any blocking collection as they rely on lock free strategies.
Take a look at the Concurrent Collections
Upvotes: 1
Reputation: 243096
The code that initializes the array is fine. You're marking the array as readonly
, which means that it is not possible to assign a new array to the _foo
field - but your code can still modify elements of the array. The operation itself will not cause crash, but if the array is changed from multiple threads, you may get unexpected results.
Without more information, it is difficult to say what the problem is. In what ways does your application crash?
Upvotes: 1