如何在 BackgroundService class 中使 ServiceBusClient 和 ServiceBusProcessor DisposeAsync?

How to make ServiceBusClient and ServiceBusProcessor DisposeAsync in BackgroundService class?

我有一个名为 'TestService' 的 class,我在 Windows 服务中使用它来接收来自 ServiceBus 队列的消息。

我的问题是,当 ServiceBusClient 和 ServiceBusProcessor 使用 DisposeAsync() 时,如何在 Dispose() 方法中正确处理 ServiceBusClient 和 ServiceBusProcessor?

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

你可以这样做

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

但您最好考虑使用 IAsyncDisposable 描述的模式来实现它 here or in the comment to this very similar question

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

示例来自 Microsoft Documentation