Search code examples
c#azureservicebus.net-core-3.1background-service

How to make ServiceBusClient and ServiceBusProcessor DisposeAsync in BackgroundService class?


I have a class called 'TestService' which I use in a Windows Service to receive message from ServiceBus queue.

My question is how to make ServiceBusClient and ServiceBusProcessor dispose properly in Dispose() method as ServiceBusClient and ServiceBusProcessor use DisposeAsync()?

public class TestService : BackgroundService
{
    private ServiceBusClient _client;
    private ServiceBusProcessor _processor;

    public TestService ()
    {            
    }

    protected async override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _client = new ServiceBusClient("myConnection");
        _processor = _client.CreateProcessor("myQueue", new ServiceBusProcessorOptions());
        _processor.ProcessMessageAsync += MessageHandler;
        await _processor.StartProcessingAsync();
    }

    public override async Task StopAsync(CancellationToken cancellationToken)
    {
        await _processor.StopProcessingAsync();            
        await base.StopAsync(cancellationToken);
    }

    public override void Dispose()
    {
         _processor.DisposeAsync(); //my question is here
         _client.DisposeAsync();    //and here
        base.Dispose();
    }

    private static async Task MessageHandler(ProcessMessageEventArgs args)
    {
        string body = args.Message.Body.ToString();

        await args.CompleteMessageAsync(args.Message);
    }
}

Solution

  • You can do it in this way

    public override void Dispose()
    {
       _processor.DisposeAsync().GetAwaiter().GetResult(); 
       _client.DisposeAsync().GetAwaiter().GetResult();
       /// [...]
    }
    

    But you should better think of implementing it with the IAsyncDisposable pattern described here or in the comment to this very similar question here

    public async ValueTask DisposeAsync(CancellationToken token)
    {
       await _processor.DisposeAsync(token); 
       await _client.DisposeAsync(token);
       /// [...]
    }
    

    Example from Microsoft Documentation