作为服务体系结构的一部分,我们有一个后台进程来监视队列并处理来自队列的消息。如果尝试停止服务,我们希望此后台进程完成当前的“批处理”,然后正常关闭。但是,这似乎没有发生(它立即死亡)。
public class MessageQueueProcessorBackground : IHostedService, IDisposable
{
private readonly IServiceProvider _services;
private readonly ILogger<MessageQueueProcessorBackground> _logger;
private bool _disposing = false;
private const int NUMBER_OF_MESSAGES_TO_PROCESS = 10;
public MessageQueueProcessorBackground(ILogger<MessageQueueProcessorBackground> logger, IServiceProvider services)
{
_logger = logger;
_services = services;
}
public void Dispose()
{
Dispose(_disposing);
}
protected virtual void Dispose(bool disposing)
{
if (!disposing)
{
_disposing = true;
}
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation($"Staring Message Queue Processor");
new Timer(BeginProcessingAsync, null, TimeSpan.Zero, TimeSpan.Zero);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation($"Stopping Message Queue Processor");
return Task.CompletedTask;
}
private void BeginProcessingAsync(object state)
{
while (!_disposing)
{
ProcessQueue();
}
}
private void ProcessQueue()
{
// does some work
}
// Finalizer to facilitate garbage collection
~MessageQueueProcessorBackground()
{
Dispose(false);
}
此过程或多或少会继续处理记录,直到没有记录为止,然后等待一会儿再尝试(等待过程在ProcessQueue代码中)。这个想法或多或少是,在处理之后调用下一个“循环”,该过程将停止并且将正常退出。这显然没有发生。这里应该更改什么?