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

查看:25
本文介绍了什么是线程安全(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) ?

感谢您的回答和时间.

我的意思是如果所有线程都只阅读 &使用(不写或改变)对象.(除了最后一个问题,很明显我的意思是线程是否同时读取和写入).因为我不知道普通访问或枚举是否是线程安全的.

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.

推荐答案

不同的情况是不同的,但总的来说,如果所有线程都在阅读,则阅读是安全的.如果有任何写入,读取或写入都是不安全的,除非它可以原子地完成(在同步块内或使用原子类型).

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).

对于字符串,你很幸运——它们是不可变的,所以你所能做的就是阅读它们.对于其他类型,您必须在阅读它们时采取预防措施,防止它们在其他线程中发生变化.

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天全站免登陆