锁定属性,好的方法? [英] Lock in properties, good approach?
问题描述
在我的多线程应用程序中,我正在使用一些变量,可以同时在许多实例中进行更改.这很奇怪,但是它工作正常,没有任何问题..但是我当然需要使其成为线程安全的.我只是从锁开始,所以我会很感激您的建议:
In my multithreading application I am using some variables that can be altered by many instances in the same time. It is weird but it has worked fine without any problem..but of course I need to make it thread-safe. I am just beginning with locks so I would appretiate your advice:
当客户端连接时,将创建客户端类,其中每个客户端都有其自己的"A"变量.
When client connects, class Client is created where each Client has its own "A" variable.
有时候,客户端调用这样的方法:
Sometimes, Client calls method like that:
Client selectedClient SelectOtherClientClassByID(sentID);
selectedClient.A=5;
到目前为止,即使在同时执行5个类(线程池)的情况下也没有问题,但是我在考虑向A属性添加锁该怎么办?
No problems until now with that even when 5 classes were doing at the same time (threadpool), but I was thinking what about adding locks to A properties?
赞:
A {
get { return mA; }
set {
// use lock here for settting A to some value
}
}
可以吗?
推荐答案
您需要同时在get和set中使用锁.此锁必须是同一对象.例如:
You need to use locks in BOTH get and set. This lock must be the same object. For example:
private object mylock = new object();
public int A {
get {
int result;
lock(mylock) {
result = mA;
}
return result;
}
set {
lock(mylock) {
mA = value;
}
}
}
这篇关于锁定属性,好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!