Skip to content

Calling channel.CloseAsync from within AsyncEventingBasicConsumer handler causes deadlock #1567

@mogzol

Description

@mogzol

Describe the bug

I am using the 7.0.0-alpha.5 release of the RabbitMQ library. In my code, under certain scenarios, the channel will be closed from within the Recieved handler of an AsyncEventingBasicConsumer. Trying to do this, however, causes a deadlock. This worked fine in v6 of this library.

Reproduction steps

Here is a simple program which reproduces the issue:

using System.Text;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;

internal class Program
{
  private static async Task Main(string[] args)
  {
    var connection = await new ConnectionFactory() { DispatchConsumersAsync = true }.CreateConnectionAsync();
    var channel = await connection.CreateChannelAsync();

    await channel.QueueDeclareAsync("testing");
    await channel.QueueBindAsync("testing", "amq.topic", "testing");

    var cancel = new CancellationTokenSource();

    var consumer = new AsyncEventingBasicConsumer(channel);
    consumer.Received += async (_, eventArgs) =>
    {
      Console.WriteLine("Received message");
      await channel.BasicCancelAsync(eventArgs.ConsumerTag);
      Console.WriteLine("Cancelled consumer");
      await channel.CloseAsync();
      Console.WriteLine("Closed channel");
      channel.Dispose();
      Console.WriteLine("Disposed channel");
      cancel.Cancel();
    };

    await channel.BasicConsumeAsync(consumer, "testing", true);

    await channel.BasicPublishAsync("amq.topic", "testing", new BasicProperties(), Encoding.UTF8.GetBytes("Hello, World!"));
    Console.WriteLine("Published message");

    try { await Task.Delay(Timeout.Infinite, cancel.Token); } catch { };
  }
}

Running this, the app will hang before "Closed channel" is logged. If you try this same code with v6 of the library (without the new Async calls) then all messaged are logged and the app exits.

Expected behavior

Closing a channel from within a consumer should not deadlock.

Additional context

No response

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions