什么是线程安全的(C#)? (字符串,数组,...?) [英] What is thread safe (C#) ? (Strings, arrays, ... ?)

查看:589
本文介绍了什么是线程安全的(C#)? (字符串,数组,...?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很新的C#,所以请多多包涵。我与线程安全的有点混乱。当东西线程安全的,当事情是​​不是?

I'm quite new to C# so please bear with me. I'm a bit confused with the thread safety. When is something thread safe and when something isn't?

阅读从外地(刚看完的东西被初始化之前)总是线程安全的?

Is reading (just reading from something that was initialized before) from a field always thread safe?

//EXAMPLE
RSACryptoServiceProvider rsa = new RSACrytoServiceProvider();
rsa.FromXmlString(xmlString);  
//Is this thread safe if xml String is predifined 
//and this code can be called from multiple threads?

时的访问从数组或列表中的对象始终是线程安全的(如果你使用一个for循环枚举)?

Is accessing an object from an array or list always thread safe (in case you use a for loop for enumeration)?

//EXAMPLE (a is local to thread, array and list are global)
int a = 0;
for(int i=0; i<10; i++)
{
  a += array[i];
  a -= list.ElementAt(i);
}

枚举始终/曾经线程安全的?

Is enumeration always/ever thread safe?

//EXAMPLE
foreach(Object o in list)
{
   //do something with o
 }

能否的写作和阅读以某一特定领域曾经导致损坏的读取(场的一半改变,一半仍是不变的)?

Can writing and reading to a particular field ever result in a corrupted read (half of the field is changed and half is still unchanged) ?

感谢您对所有的答案和时间。

Thank you for all your answers and time.

编辑:我的意思是,如果所有线程都只能读,放大器;使用(不写或改变)对象。 (除了最后一个问题在这里很明显,我的意思是,如果线程读取和写入)。因为我不知道,如果普通访问或枚举是线程安全的。

I meant if all threads are only reading & using (not writing or changing) object. (except for the last question where it is obvious that I meant if threads both read and write). Because I do not know if plain access or enumeration is thread safe.

推荐答案

这是不同的情况不同的,但一般来说,阅读是,如果所有线程都读安全。如果有任何正在写,无论是读或写是安全的,除非它可以自动完成的(synchronized块内或原子类型)。

It's different for different cases, but in general, reading is safe if all threads are reading. If any are writing, neither reading or writing is safe unless it can be done atomically (inside a synchronized block or with an atomic type).

这是不明确的,阅读是确定的 - 你永远不知道什么是罩下发生的 - 例如,一个getter可能需要在第一次使用(因此写入本地字段)初始化数据

It isn't definite that reading is ok -- you never know what is happening under the hoods -- for example, a getter might need to initialize data on first usage (therefore writing to local fields).

对于字符串,你是幸运的 - 他们是不可改变的,因此,所有你能做的就是阅读。与其他类型的,你将不得不采取precautions对他们在其他线程改变,而你正在阅读。

For Strings, you are in luck -- they are immutable, so all you can do is read them. With other types, you will have to take precautions against them changing in other threads while you are reading them.

这篇关于什么是线程安全的(C#)? (字符串,数组,...?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆