CodeQL 文档

非静态上下文中对静态集合成员的非同步访问

ID: cs/unsynchronized-static-access
Kind: problem
Security severity: 
Severity: error
Precision: medium
Tags:
   - concurrency
   - external/cwe/cwe-362
   - external/cwe/cwe-567
Query suites:
   - csharp-security-and-quality.qls

点击查看 CodeQL 存储库中的查询

出于性能原因,标准库中的大多数集合类都不是线程安全的,而是要求用户通过外部锁定或数据结构不变量来保证一次最多从一个线程使用它们。

例如,当写入与另一个写入或读取同时发生时,Dictionary 的行为未定义,并且经常导致数据损坏,并且可能导致诸如活锁之类的严重问题。

建议

如果可能从多个线程访问静态数据成员(例如 Dictionary),请确保它是并发安全的集合类型,或者所有读取和写入都由合适的锁或监视器保护。

示例

以下代码使用静态字典来存储属性,但提供对该字典的非同步访问。这意味着多个线程可以访问该字典,从而可能导致竞争条件。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Threading;

public class Configuration
{
    public static Dictionary<string, string> properties = new Dictionary<string, string>();

    // called concurrently elsewhere
    public string getProperty(string key)
    {
        // BAD: unsynchronized access to static collection
        return dict["foo"];
    }
}

参考

  • ©GitHub 公司
  • 条款
  • 隐私