这个方法线程安全吗?

Mar*_*rco 1 .net c# multithreading

如果以下方法是线程安全的,请有人告诉我.另外,请假设对_cache.GetOrCreate(...)的调用是线程安全的.此方法是创建或更新区域(字典)的应用程序中的唯一位置.包含此方法的类是单例,因此多个线程将访问它.

    public IEnumerable<string> GetReportLookupItems<T>(string cacheKey, Func<IEnumerable<string>> factory)
    {
        Dictionary<string, IEnumerable<string>> region = _cache.GetOrCreate("Cache-Region:LookupItems", () => new Dictionary<string, IEnumerable<string>>());

        IEnumerable<string> items;

        if (!region.TryGetValue(cacheKey, out items))
        {
            region[cacheKey] = items = factory();
        }

        return items;
    }     
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 5

不,这绝对不是线程安全的.

你正在使用Dictionary<T,U>这里,并改变其内容.由于Dictionary<T,U>不是线程安全的,因此TryGetValue按键调用和设置字典不是线程安全的.

如果要将其更改为使用线程安全字典(例如ConcurrentDictionary<T,U>),则可能会将此作为线程安全方法.

  • 但请注意,即使使用`ConcurrentDictionary`,首先调用`TryGetValue`并随后添加该值也不是线程安全的.相反,需要使用`GetOrAdd`. (3认同)