从BackgroundService启动Service Bus客户端

时间:2019-08-18 21:17:10

标签: .net-core azureservicebus asp.net-core-hosted-services

我有一个ServiceBusClient类,它创建一个QueueClient,该类用于侦听总线上的消息。我看过以下文章来进行设置:

Background tasks (Microsoft)

Hosted services (Microsoft)

Async and Await

我处理ServiceBusClient的{​​{1}}类看起来像这样:

QueueClient

我希望从public class ServiceBusClient : IServiceBusClient { public ServiceBusClient(IEventService eventService, ServiceBusClientOptions options) { ... queueClient = new QueueClient(options.ConnectionString, options.QueueName); } public void Run() { RegisterOnMessageHandler(); } private void RegisterOnMessageHandler() { ... queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions); } private async Task ProcessMessagesAsync(Message message, CancellationToken token) { var eventMessage = EventMessage.FromMessage(message); await eventService.Write(eventMessage); if (!token.IsCancellationRequested) { await queueClient.CompleteAsync(message.SystemProperties.LockToken); } } private Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs) { // log errors ... return Task.CompletedTask; } } 启动,甚至希望扩展IHostedService。在我发现的示例中,工作总是在while循环中执行,这不适合我的情况,因为我仅尝试运行单个命令。

所以我创建了一个超级简单的实现,像这样:

BackgroundService

如果删除protected override async Task ExecuteAsync(CancellationToken cancellationToken) { serviceBusClient.Run(); while (!cancellationToken.IsCancellationRequested) { // empty loop to keep running for lifetime of pod } } ,显然我需要返回一些东西。我尝试了async,但这需要将返回类型更改为Task.CompletedTask

如果我有Task<Task>,我将需要async,但是我不确定是什么。

这感觉不对。我以为我需要在await中进行一些更改,但是我不确定是什么,因为ServiceBusClient是异步的,并且根据我的理解在后台进行了繁重的工作。

我想要的只是让我的网络应用开始监听消息,直到消息消失。我该怎么办?

1 个答案:

答案 0 :(得分:1)

我放弃使用BackgroundService,而是改用了IHostedService

    public class MessageListenerService : IHostedService
    {
        private readonly IServiceBusClient client;
        private readonly ITelemetryClient applicationInsights;

        public MessageListenerService(IServiceProvider serviceProvider)
        {
            client = serviceProvider.GetService<IServiceBusClient>();
            applicationInsights = serviceProvider.GetService<ITelemetryClient>();
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            applicationInsights.TrackTrace(new TraceTelemetry("MessageListenerService is starting"));

            client.Run();

            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            applicationInsights.TrackTrace(new TraceTelemetry("MessageListenerService is stopping"));
            return client.Stop();
        }
    }

如果您发现此代码有问题,请在评论中告知我,我们将酌情进行更新。

最后我们还是为此创建了一个控制台应用程序。