csredis icon indicating copy to clipboard operation
csredis copied to clipboard

A memory leak occurs at CSRedisClient

Open whiteneon1017 opened this issue 2 years ago • 1 comments

If you create an instance of CSRedisClient and release it repeatedly, about 36 bytes will be leaked each time. To resolve the problem, it is necessary to write the Dispose method in the following three places.

leak test tool

{
    for (int index = 0; ; index++)
    {
        System.Threading.Thread.Sleep(1000);

        client = new CSRedisClient(url);

        client.Dispose();
        client = null;
    }
}

Additions

    public partial class CSRedisClient : IDisposable
    {
        public void Dispose()
        {
            foreach (var pool in this.Nodes.Values) pool.Dispose();
            SentinelManager?.Dispose();

            this.Nodes.Clear(); //add
            this.NodesKey.Clear(); //add
            this.NodesIndex.Clear(); //add
            this.SlotCache.Clear(); //add
            this._rnd = null; //add
            this.NodesServerManager = null; //add
            this.NodeRuleRaw = null; //add
            this.NodeRuleExternal = null; //add
            this.NodesLock = null; //add
            this.BackgroundGetSentinelMasterValueIngLock = null; //add
        }
    }

    public partial class RedisClient : IRedisClientSync, IRedisClientAsync
    {
        /// <summary>
        /// Dispose all resources used by the current RedisClient
        /// </summary>
        public void Dispose()
        {
            Socket.Dispose(); //add
            _subscription.MessageReceived -= OnSubscriptionReceived; //add
            _subscription.Changed -= OnSubscriptionChanged; //add
            _monitor.MonitorReceived -= OnMonitorReceived; //add
            _connector.Connected -= OnConnectionConnected; //add
            _transaction.TransactionQueued -= OnTransactionQueued; //add
            
            _connector.Dispose();
        }
    }
    public class RedisClientPool : ObjectPool<RedisClient>
    {
        public new void Dispose() //add
        {
            base.Dispose();

            if (_policy != null)
            {
                _policy._pool = null;
                _policy = null;
            }

            Encoding = null;
        }
    }

whiteneon1017 avatar Oct 17 '23 09:10 whiteneon1017

see https://github.com/2881099/FreeRedis

2881099 avatar Oct 18 '23 04:10 2881099