在多线程代码中,当一个实例可能被多个线程读取或写入时,它们需要被锁定以安全地执行这些操作。
为了避免重复创建要锁定的对象并通过代码编写一堆锁定语句,我创建了一个通用类来处理锁定。
从概念上讲,我错过了什么吗?这应该有效,对吧?
public class Locked<T> where T : new()
{
private readonly object locker = new object();
private T value;
public Locked()
: this(default(T))
{ }
public Locked(T value)
{
this.value = value;
}
public T Get()
{
lock (this.locker)
{
return this.value;
}
}
public void Set(T value)
{
lock (this.locker)
{
this.value = value;
}
}
}
还有一个在类中使用它的例子:
private Locked<bool> stopWorkerThread = new Locked<bool>();
public void WorkerThreadEntryPoint()
{
while (true)
{
if (this.stopWorkerThread.Get())
{
break;
}
另外,我将如何以自动化的方式测试这样的东西(例如创建一个单元测试)?
最后,我可以做些什么来实现 ++ 和 -- 运算符,以避免这种情况:
this.runningThreads.Set(this.runningThreads.Get() + 1);