我是否需要在ASP.NET Core中锁定单例?

Ale*_*kiy 7 c# singleton multithreading asp.net-core

这是我的代码:

public class RouteSingleton
{
    private IDictionary<string, string> _dealCatLinks;
    private IDictionary<string, string> _sectionLinks;
    private IDictionary<string, string> _categoryLinks;
    private IDictionary<string, string> _materials;
    private IDictionary<string, string> _vendors;
    public RouteSingleton(IDealService dealService
        , ICategoryService categoryService
        , IVendorService vendorService)
    {


        this._dealCatLinks = dealService.GetDealCatLinks("PLV").Distinct().ToDictionary(x => x, x => x);
        this._sectionLinks = categoryService.GetSectionLinks("PLV").Distinct().ToDictionary(x => x, x => x);
        this._categoryLinks = categoryService.GetMainCategoryLinks("PLV")
            .Where(x => !_sectionLinks.ContainsKey(x)).Distinct().ToDictionary(x => x, x => x);
        this._vendors = _vendorService.GetVendorLinks("PFB").Distinct().ToDictionary(x => x, x => x);

    }

    public bool IsDealCategory(string slug)
    {
        return _dealCatLinks.ContainsKey(slug);
    }

    public bool IsSectionUrl(string slug)
    {
        return _sectionLinks.ContainsKey(slug);
    }

    public bool IsCategory(string slug)
    {
        return _categoryLinks.ContainsKey(slug);
    }       

    public bool IsVendor(string slug)
    {
        return _vendors.ContainsKey(slug);
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是我注册的方式startup.cs:

services.AddSingleton<RouteSingleton, RouteSingleton>();
Run Code Online (Sandbox Code Playgroud)

我像这样使用singletonin route constraints:

routes.MapRoute("category", "{slug}", defaults: new { controller = "Category", action = "Index" }, constraints: new { slug = new CategoryConstraint(app.ApplicationServices.GetRequiredService<RouteSingleton>()) });
Run Code Online (Sandbox Code Playgroud)
  1. 我想我是否需要lock threads在我RouteSingleton.cs或我的代码中在许多用户的应用程序启动下工作正常?
  2. 如果我需要锁定你可以向我建议的方式?
  3. 如果我不这样做会怎样?

Tim*_*Tim 8

不,你不需要锁定任何东西.它是一个单独的,只会被构造一次,并且您在多个线程中同时使用私有字典进行的唯一操作是调用ContainsKey,这应该是非常安全的,因为在您调用时没有其他任何东西可以修改字典ContainsKey.

但是,如果你在构造函数之后修改这些字典,那将是一个完全不同的故事 - 你要么必须使用锁/互斥锁等.保护对它们的访问或使用线程安全字典,例如ConcurrentDictionary.正如目前所写,你应该没事.