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
c # asynchronous async-await


source to share


No one has answered this question yet

Check out similar questions:

5129
How do I return a response from an asynchronous call?
3575
How to list a transfer?
2817
How can I upload files asynchronously?
1137
How can I get jQuery to make a synchronous rather than asynchronous Ajax request?
957
How and when to use "async and await"
600
How can I run the async Task <T> method synchronously?
123
Is the async HttpClient from .Net 4.5 a bad choice for heavy load applications?
44
Fire and forget async method in asp.net mvc
4
Changing an asp.net application to use async little by little
3
How to implement command pattern using async / await



All Articles
Loading...
X
Show
Funny
Dev
Pics