nats-io / stan.net

The official NATS .NET C# Streaming Client
Apache License 2.0
137 stars 41 forks source link

stanConnection.Subscribe async message handler #157

Open robertmircea opened 4 years ago

robertmircea commented 4 years ago

Would it be possible to introduce an async message handler for Subscribe method? I would like to be able to await inside message handler and properly handle exceptions thrown.

hopedrivendeveloper commented 4 years ago

Hi @robertmircea. Would following code work for you?

using (var connection = conn.GetIStanConnection())
{
    var ev = new AutoResetEvent(false);

    using (var s = connection.Subscribe(topicName, "procesorGroupName", opts, MessageHandler))
    {
        Log.Information("Waiting on messages from {topic}.", topicName);
        ev.WaitOne();
    }

    async void MessageHandler(object sender, StanMsgHandlerArgs arg)
    {
        try
        {
            await DoSomethingWithMessageAsync(Encoding.UTF8.GetString(arg.Message.Data)));
        }
        catch (Exception e)
        {
            Log.Error("Processing {message} failed with an {@error}.", message, e);
        }
        finally
        {
            arg.Message.Ack();
        }
    }
}
fraliv13 commented 3 years ago

When using ManualAcks = false are there any options besides blocking the thread?