gpt4 book ai didi

c# - 是否有一些 Visual Studio 扩展可以检查代码是否存在潜在的线程不安全性?

转载 作者:行者123 更新时间:2023-11-30 23:11:11 25 4
gpt4 key购买 nike

是否有一些 Visual Studio 扩展可以检查代码中潜在的线程不安全性并标记这段代码?也许 ReSharper 具有此功能?

最佳答案

我知道有两种 R# 检查。

对于lock-statements

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;
}
}

关于c# - 是否有一些 Visual Studio 扩展可以检查代码是否存在潜在的线程不安全性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44891800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com