2881099 / csredis

.NET Core or .NET Framework 4.0+ client for Redis and Redis Sentinel (2.8) and Cluster. Includes both synchronous and asynchronous clients.
MIT License
2.01k stars 414 forks source link

A memory leak occurs at CSRedisClient #488

Open whiteneon1017 opened 11 months ago

whiteneon1017 commented 11 months ago

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;
        }
    }
2881099 commented 11 months ago

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