是否有一些Visual Studio扩展,检查代码是否存在潜在的线程不安全并标记这段代码?也许ReSharper有这个能力?
答案 0 :(得分:2)
我知道有两次R#检查。
适用于lock
- 语句
public class SometimesNotSynchronizedWarning
{
private readonly List<string> _list = new List<string>();
private readonly object _lockObj = new object();
public bool Contains(string item)
{
lock (_lockObj)
{
return _list.Contains(item);
}
}
public void Add(string item)
{
// R# warning: "The field is sometimes used inside synchronized block
// and sometimes used without synchronization":
_list.Add(item);
}
}
用于双重检查锁定实施
public class DoubleCheckedLockingWarning
{
private List<string> _instance;
private readonly object _lockObj = new object();
public List<string> GetInstance()
{
if (_instance != null) return _instance;
lock (_lockObj)
if (_instance == null)
// R# warning: "Possible incorrect implementation of Double-Check Locking.
// Checked field must be volatile or assigned from local variable
// after 'Thread.MemoryBarrier()' call":
_instance = new List<string>();
return _instance;
}
}