azureazure-functionsservicebusobjectdisposedexception

Azure Functions: Servicebustrigger -> BrokeredMessage been disposed


I been writting alot of Webjobs with similar functionallity where similar code works just fine. But with Azure Functions instead I get error sometimes.

[FunctionName("Alert")]
public static async void Alert([ServiceBusTrigger(Topic.Alert, Subscription.Sql, AccessRights.Listen, Connection = "servicebusconnectionstring")] BrokeredMessage message, TraceWriter log)
{
    using (var stream = message.GetBody<Stream>())
    {
        using (var memoryStream = new MemoryStream())
        {
            stream.CopyTo(memoryStream);
            var json = Encoding.UTF8.GetString(memoryStream.ToArray());

            try
            {
                throw new Exception("Test-Exception");
            }
            catch (Exception e)
            {
                EventLogger.LoggException("Function.Sql.Alert", e, new Dictionary<string, string>() { { "Messsage", json } });
                if (message.DeliveryCount >= 5)
                {
                    EventLogger.LoggEvent("DeadLetterQueue", new Dictionary<string, string>() { { "Function", "Function.Sql.Alert" }, { "Messsage", json } });
                    await QueueService.SendAsync(Queue.Deadletter, JsonConvert.DeserializeObject<CloudAlert>(json));
                    await message.CompleteAsync();
                }
                else
                    await message.AbandonAsync();
            }
        }
    }
    await message.CompleteAsync();
}

The issue is when I call message.AbandonAsync() or message.CompleteAsync it sometimes throw

System.ObjectDisposedException: BrokeredMessage has been disposed.

If I don't call message.CompleteAsync() at the end the message is still marked as completed. I could live with that, but I want to be able to Abandon the message as well and that function dosn't always work either.

Someone done something similar and have a solution? Using .NET Standard 2.0 and following NuGet package for ServiceBus: Microsoft.Azure.ServiceBus v2.0.0


Solution

  • You should not Complete or Abandon messages manually. Azure Functions runtime will do it for you based on success of failure (exception) of your function execution.

    So, throw an exception if you want to Abandon. It will be auto-retried again up until Max Delivery Count limit.