Leroy Jenkins
Leroy Jenkins

Reputation: 2770

Thread safe array

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

Answers (3)

Tomas Panik
Tomas Panik

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>
  • also consider BlockingCollection<T> for Producer-Consumer scenarios

Upvotes: 0

oleksii
oleksii

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

Tomas Petricek
Tomas Petricek

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

Related Questions