简体   繁体   English

c#基本数组易变吗?

[英]are c# primitive arrays volatile?

I declare array like that private double[] array = new double[length] . 我声明像private double[] array = new double[length] Is it safe to update this array items in one thread and read in another thread? 在一个线程中更新此数组项并在另一个线程中进行读取是否安全? Will I have up to date value? 我会拥有最新的价值吗?

Note i do not enumerate array. 注意我不列举数组。 I only access its items by index. 我仅按索引访问其项目。

Arrays are not thread safe, from MSDN : 来自MSDN的数组不是线程安全的:

Enumerating through a collection is intrinsically not a thread-safe procedure. 通过集合进行枚举本质上不是线程安全的过程。 Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. 即使同步了一个集合,其他线程仍然可以修改该集合,这将导致枚举器引发异常。 To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads. 为了保证枚举期间的线程安全,您可以在整个枚举期间锁定集合,也可以捕获由其他线程进行的更改导致的异常。

If you only update single items at a time I think that you will be safe though, but I would not trust it unless I found documentation that proves it. 如果您一次只更新单个项目,我认为您将是安全的,但是除非找到能够证明这一点的文档,否则我将不信任它。

Volatile does not guarantee freshness of a value. 挥发性不保证价值的新鲜度。 It prevents some optimizations, but does not guarantee thread synchronization. 它阻止了一些优化,但不保证线程同步。

Double is not guaranted to be updated atomically . Double不保证会自动进行原子更新 So updating/reading arrays of doubles without synchronization will not be thread safe at all wit or without volatile as you may read partially written values. 因此,不同步就更新/读取双精度数组将根本不是线程安全的,也不是不稳定的,因为您可能会读取部分写入的值。

No, they are not. 不,他们不是。 You should design your locking system with semaphores or other methods to ensure thread safety. 您应使用信号量或其他方法设计锁定系统,以确保线程安全。 You can check producer/consumer problem . 您可以检查生产者/消费者问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM