stan.net icon indicating copy to clipboard operation
stan.net copied to clipboard

stanConnection.Subscribe async message handler

Open robertmircea opened this issue 5 years ago • 2 comments

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.

robertmircea avatar Nov 22 '19 19:11 robertmircea

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();
        }
    }
}

hopedrivendeveloper avatar Nov 22 '19 23:11 hopedrivendeveloper

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

fraliv13 avatar Jan 21 '21 11:01 fraliv13