如何在 BackgroundService 类中制作 ServiceBusClient 和 ServiceBusProcessor DisposeAsync?

Posted

技术标签:

【中文标题】如何在 BackgroundService 类中制作 ServiceBusClient 和 ServiceBusProcessor DisposeAsync?【英文标题】:How to make ServiceBusClient and ServiceBusProcessor DisposeAsync in BackgroundService class? 【发布时间】:2022-01-09 18:42:12 【问题描述】:

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

我的问题是如何使 ServiceBusClient 和 ServiceBusProcessor 在 Dispose() 方法中正确处理,因为 ServiceBusClient 和 ServiceBusProcessor 使用 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);
    

【问题讨论】:

关于这个问题的任何更新?这个答案解决了你的问题吗? @DeepDave-MT 您好,已排序。 【参考方案1】:

你可以这样做

public override void Dispose()

   _processor.DisposeAsync().GetAwaiter().GetResult(); 
   _client.DisposeAsync().GetAwaiter().GetResult();
   /// [...]

但您最好考虑使用here 中描述的IAsyncDisposable 模式或在对这个非常相似的问题here 的评论中实现它

public async ValueTask DisposeAsync(CancellationToken token)

   await _processor.DisposeAsync(token); 
   await _client.DisposeAsync(token);
   /// [...]

来自Microsoft Documentation的示例

【讨论】:

您好,感谢您的回答。你是说 TestService 应该从 IHostedService 继承,IAsyncDisposable 然后我们有 DisposeAsync? @anhtv13 正确。 @anhtv13 这解决了你的问题吗? 好的,非常感谢。

以上是关于如何在 BackgroundService 类中制作 ServiceBusClient 和 ServiceBusProcessor DisposeAsync?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 ASP.NET Core 2.1 中的计时器上运行 BackgroundService

在PPT中制格封面怎样操作?一招教你轻松解决作

从 BackgroundService 创建 DbContext 租户时配置它

从asp.net core 2.1中的控制器访问BackgroundService

android localytics 4.5.1 崩溃 NoClassDefFoundError com.localytics.android.BackgroundService

.NET Worker Service 如何优雅退出