开发者

C# thread safety for class instances

开发者 https://www.devze.com 2023-02-04 10:04 出处:网络
I am learning C# and I am confused with the thread safety of the copies of the class instances as below:

I am learning C# and I am confused with the thread safety of the copies of the class instances as below:

eg:
  classA objA;
  classA objB = objA;

  objA.field1 = value2; //do I need lock around modification of field1?

  //let say we pass the objB to another thread
  objB.field1 = value1 //do I need a lock for objB because of the modification of field1开发者_Python百科?

I am confused because coming from the background of C++, the class in C# is the reference type. If both objA and objB refer to the same memory underlying, then I would need a lock to protect the simultaneous writing to the field1. Could someone confirm with this or am I missing something?

Thanks.


You mention your C++ background so perhaps you could think of your C# code as this C++ code:

classA objA;
classA &objB = objA; //note reference

objA.field1 = value2; //do I need lock around modification of field1?
                      //Answer : yes if someone else has access to the object

You should lock your object if modified/mutated by multiple threads. That can be done easily using a property rather than a public field. Or using a simple method.

There may be times when modifying a primitive type does not require a lock. But locking is the simplest and safest solution to most situations regarding concurrent access/mutation.

//let say we pass the objB to another thread
//do I need a lock for objB because of the modification of field1?
Thread newThread = new Thread((classB b) => b.field1 = value1);

Yes, providing the object is mutable.


It depends. According to the specification the following types are atomic:
bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types.

If field1 is one of those or a reference you don't need a lock if you don't have any further dependencies.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号