Do I need to lock singleton in ASP.NET Core?

邮差的信 提交于 2020-01-01 09:27:08

问题


Here is my code:

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

Here is how I register in startup.cs:

services.AddSingleton<RouteSingleton, RouteSingleton>();

And I use the singleton in route constraints like so:

routes.MapRoute("category", "{slug}", defaults: new { controller = "Category", action = "Index" }, constraints: new { slug = new CategoryConstraint(app.ApplicationServices.GetRequiredService<RouteSingleton>()) });
  1. I wonder do I need to lock threads in my RouteSingleton.cs or my code will work fine under lots of users on application start?
  2. If I need to lock what way you can suggest to me?
  3. What will happen if I don't?

回答1:


No, you don't need to lock anything. It is a singleton and will only be constructed once, and the only thing you are doing with your private dictionaries in multiple threads simultaneously is calling ContainsKey, which should be quite safe since nothing else can be modifying the dictionary while you are calling ContainsKey.

However, if you were modifying those dictionaries after the constructor, it would be an entirely different story-- you would either have to use a lock/mutex/etc. to protect access to them or use a thread safe dictionary, such as ConcurrentDictionary. As it is currently written, you should be fine.



来源:https://stackoverflow.com/questions/45527228/do-i-need-to-lock-singleton-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!