我有一个简单的类,我想让它成为线程安全的。该类需要实现 IComparer。我知道int CompareTo(T other)
以线程安全的方式实现它并不是直截了当的。如果我没有以正确的方式锁定,很容易出现死锁。我有三个问题:
- 这段代码是线程安全的吗?如果没有,我该如何解决?
- 这段代码可以更短吗?一个简单的减法似乎有很多代码。
- 我什至应该费心使
int CompareTo(T other)
线程安全吗?我是否应该要求调用者(通常是排序)锁定所有相关的 BObject?
这是我的代码:
public class BObject : IComparable<BObject>
{
//Each BObject has a unique object id
private static int _bObjectId = 0;
private static int GetNextId()
{
return System.Threading.Interlocked.Increment(ref BObject._bObjectId);
}
private object _locker = new object();
private readonly int _id = BObject.GetNextId();
//Some variable
private int _sales;
public int Sales
{
get
{
lock (this._locker)
return this._sales;
}
set
{
lock (this._locker)
this._sales = value;
}
}
public int CompareTo(BObject other)
{
int result;
//Can I simply do "if (this._id == other._id)"
if (object.ReferenceEquals(this, other))
result = 0;
else
{
//get the BObject with the lower id
BObject lower = this._id < other._id ? this : other;
//get the BObject with the higher id
BObject higher = this._id > other._id ? this : other;
//lock the BObject with the lower id first
lock (lower._locker)
{
//lock the BObject with the higher id last
lock (higher._locker)
{
//put object with lower Sales first
result = this.Sales - other.Sales;
}
}
}
return result;
}
}