pardahlman / RawRabbit

A modern .NET framework for communication over RabbitMq
MIT License
743 stars 142 forks source link

Memeory leak when using ChannelFactory to create channels #339

Open Ankurkh1 opened 6 years ago

Ankurkh1 commented 6 years ago

Hi @pardahlman

Once again thanks for this awesome library. If we try to create channels using Channel factory it keeps leaking memory. Even if we explicitly dispose it(or in using scope). My memory profiling tells me protected readonly ConcurrentBag Channels; is holding on to the the reference and so GC can never release it.

I think this factory class should not worry about the lifetime of the channel and let the creater manage it.

pardahlman commented 6 years ago

Hello @Ankurkh1 - thanks for reporting this. I think what you are proposing makes a lot of sense. Feel free to submit a PR with the change proposed 👍

worldbeater commented 5 years ago

Resolved this by introducing a RawRabbit connection pool as IDictionary<string, IBusClient>, where string is RabbitMQ connection string. However, it works only if you need to send a lot of messages to a little amount of queues. If you need to send a lot of messages to a lot of queues, then this won't work — still searching for a solution that covers such cases as well.

public class QueueManager {
    private readonly IDictionary<string, IBusClient> _clients = 
        new ConcurrentDictionary<string, IBusClient>();

    public async Task SendMessage(string connectionString) {
        var connection = ConnectionStringParser.Parse(connectionString);
        if (!_clients.TryGetValue(connectionString, out var bus))
            bus = _clients[connectionString] = BusClientFactory.CreateDefault(connection);
        await bus.PublishAsync(...);
    }
}