开发者

c# Threading locking for 2 fields of a class

开发者 https://www.devze.com 2023-01-30 08:33 出处:网络
The question is easy, suppose I have开发者_开发百科: class MyClass { object myObj1 object myObj2 } Thread1(MyClass c)

The question is easy, suppose I have开发者_开发百科:

class MyClass
{
    object myObj1
    object myObj2
}

Thread1(MyClass c)
{
    DoALotOnMyObj1(c.myObj1);
}

Thread2(MyClass c)
{
    DoALotOnMyObj2(c.myObj2);
}

Do I have to use locks in this case, even if I'm totally sure that both threads will use only myObj1 (or 2 depending on thread) and not the other field?


No, you would not.


The concept of having a lock is to make sure that while you are changing a resource in one thread, other threads do not access it until the lock is released.

In your case, you are not sharing any resources between the two threads, so you don't need to have a lock.

0

精彩评论

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

关注公众号