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

时间:2017-08-05 23:25:53

标签: c# multithreading asp.net-core singleton

这是我的代码:

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

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

services.AddSingleton<RouteSingleton, RouteSingleton>();

我使用singleton中的route constraints就像这样:

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

1 个答案:

答案 0 :(得分:6)

不,你不需要锁定任何东西。它是一个单独的,只能构造一次,而你在多个线程中同时使用私有字典进行的唯一事情就是调用ContainsKey,这应该是非常安全的,因为当你还没有别的东西可以修改字典致电ContainsKey

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