Problems Using Static MemcachedClient

I use Memcached to store data for quick access. I read that creating MemcachedClient is expensive and considering using MemcachedClient as static (see link )

Therefore, I used the Singleton template for my client as:

public class CommonObjectsCache
{
    private static CommonObjectsCache _cache;
    private static MemcachedClient _client;

    public static MemcachedClient Client
    {
        get
        {
            if (_client == null)
                _client = new MemcachedClient();

            return _client;
        }
        private set
        {
            _client = value;
        }
    }

    private CommonObjectsCache()
    {
        _client = new MemcachedClient();
    }

    public static CommonObjectsCache Cache
    {
        get
        {
            if (_cache == null)
                _cache = new CommonObjectsCache();

            return _cache;
        }
    }
}

In my DAL, I use them as follows:

    public static List<Item1> AllItem1s
    {
        get
        {
            if (CommonObjectsCache.Client.Get<List<Item1>>("AllItem1s") == null)
                RefreshItem1Cache();

            return CommonObjectsCache.Client.Get<List<Item1>>("AllItem1s");
        }
        private set
        {
            CommonObjectsCache.Client.Store(StoreMode.Set, "AllItem1s", value);
        }
    }
    public static List<Item2> AllItem2s
    {
        get {  // Same as above }
        private set { // Same as above }
    }
    public static List<Item3> AllItem3s
    {
        get {  // Same as above }
        private set { // Same as above }
    }
    public static List<Item4> AllItem4s
    {
        get {  // Same as above }
        private set { // Same as above }

    }

And fill them in as:

public static void RefreshItem1Cache()
{
    List<Item1> items = (from i ctx.Item1
                        select i).ToList();
    AllItem1s = items;
}

In my DAL code, I have a method like:

public static MyModel GetMyModel(int? id)
{
    // I use AllItem1s here.
}

When I run the code, it sometimes says that AllItem1s.Count == 0, but when I put a breakpoint and diagnose this value in AllItem1, I see that it is full. So, I updated the code as follows to check if I am not mistaken:

public static MyModel GetMyModel(int? id)
{
    if (AllItem1s == null || AllItem1s.Count == 0 || AllItem2s == null || AllItem2s.Count == 0 || AllItem3s == null || AllItem3s.Count == 0 || AllItem4s == null || AllItem4s.Count == 0)
    {
        string msg = "Error!!!!!";
    }
    // I use AllItem1s here.
}

And surprisingly, the code drops to string msg = "Error!!!!!";block !!!

if Count , , thay .

, , AllItemXs. , , ( , , getter ).

- , isue?

+4
1

singleton . , ( ) : () CommonObjectsCache.

.

Google singleton #.

+2

Source: https://habr.com/ru/post/1658211/


All Articles