代码检查:获取锁的顺序不一致
如果您的类有多个资源通过锁保护以实现线程安全,ReSharper 会分析多线程环境中的可能执行路径(假设类的公共 API 可以被多个线程同时使用)以及这些执行路径上获取锁的顺序,以查找可能在运行时导致死锁的循环,如下例所示。 警告消息提供了详细的解释以及可能形成的循环的示例。
class MultiThreadedComponent
{
private List<string> _resource1 = new();
private List<string> _resource2 = new();
public void PublicApi01()
{
lock (_resource1)
lock (_resource2)
{
// do work
}
}
public void PublicApi02()
{
lock (_resource2)
{
// do work
HelperMethod02();
// do work
}
}
private void HelperMethod02()
{
// The expression is used in several lock statements with inconsistent execution order,
// forming a cycle. This might lead to a possible deadlock if methods (properties)
// of this type are executed concurrently by multiple threads.
// Lock objects involved in the cycle: '_resource1', '_resource2'
// Example of the deadlock situation:
// - Thread #1 executes 'PublicApi01', takes locks '_resource1' -> '_resource2'
// - Thread #2 executes 'PublicApi02', takes locks '_resource2' -> '_resource1'
lock (_resource1)
{
// do work
}
}
}
最后修改日期: 2025年 9月 27日