How to implement delegates that are async safe

I have Subscriber.cs

one that takes an action, listens to the RabbitMQ queue and performs the specified action on any message from that queue:

public class Subscriber {

     public Subscriber(Action<T> consumeMessage)
            {
                _consumeMessage = consumeMessage;
            }

            ....

            void HandleMessage(T message) {
                    try
                    {
                          _consumeMessage(message);                          
                    }
                    catch (Exception e)
                    {                 
                        _logger.LogError("Some error message");
                    }
            }
    }

      

This worked fine until I (accidentally) provided an async function:

 var subscriber = new Subscriber<MyMessage>(
                consumeMessage: message =>
                {
                    messageHandler.HandleAsync(message);
                });

      

Performs an action in fire and forget mode that still works when it works, but fails when it fails.

So I tried this:

   var subscriber = new Subscriber<MyMessage>(
                    async consumeMessage: message =>
                    {
                        await messageHandler.HandleAsync(message);
                    });

      

It certainly looks pretty nice, but somehow throws an exception in that snippet (and not internally Subscriber

), causing the whole application to crash.

So I tried this:

   var subscriber = new Subscriber<MyMessage>(
                    consumeMessage: message =>
                    {
                        messageHandler.HandleAsync(message).GetAwaiter().GetResult();
                    });

      

This works as intended, but can lead to deadlock (if I believe on the internet).

It also makes mine a Subscriber

very unfriendly and dangerous component to use, as the first two examples will compile even if they don't actually work.

How do I create my component Subscriber

so that it can work safely with async delegates?

+3


source to share





All Articles