线程安全数组
我不擅长多线程,但自从我将以下行添加到我的应用程序后,它似乎经常崩溃,所以我假设它不是线程安全的。
private readonly string[] _foo = Enumerable.Range(1, 1000).Select(i => i.ToString()).ToArray();
我有什么选择可以使该线程安全?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
初始化数组的代码很好。您将数组标记为
readonly
,这意味着无法将新数组分配给_foo
字段 - 但您的代码仍然可以修改数组的元素。操作本身不会导致崩溃,但如果从多个线程更改数组,则可能会得到意想不到的结果。如果没有更多信息,很难说问题是什么。您的应用程序以什么方式崩溃?
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?
如果您使用 C# 4,您可以使用一些已经内置的集合。它们比任何阻塞收集都要快,因为它们依赖于无锁策略。
查看并发集合
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
List
或T[]
-->SynchronizedCollection
(请注意,枚举不是线程安全的)Dictionary
-->ConcurrentDictionary
Queue
-->ConcurrentQueue
Stack
-->ConcurrentStack
BlockingCollection
List<T>
orT[]
-->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 scenarios