csredis icon indicating copy to clipboard operation
csredis copied to clipboard

RedisHelper.Subscribe 订阅channel后, 需要调用异步方法处理业务

Open bbenph opened this issue 3 years ago • 0 comments

我遇到了个问题, redis 订阅channel后需要 调用一个异步方法去处理, 但是 RedisHelper.Subscribe 只提供了同步Action方法参数, 如果强行使用 .Result 会导致线程饥荒的问题 请教下作者有什么好建议 `public class testSubscriber : BackgroundService { private readonly Logger _logger;

    public testSubscriber(IServiceProvider services)
    {
        Services = services;
        _logger = LogManager.GetCurrentClassLogger();
    }

    public IServiceProvider Services { get; }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {


        await DoWork(stoppingToken);
    }

    private async Task DoWork(CancellationToken stoppingToken)
    {
        RedisHelper.Subscribe(
          ("channel1", msg =>
          {
              await HandlerAsync(msg.Body);
          }
        ),
          ("channel2", msg =>
          {
              Console.WriteLine(msg.Body);
          }));
    }

    private async Task<int> HandlerAsync(string jh)
    {
        using (var scope = Services.CreateScope())
        {
            var scopedProcessingService = scope.ServiceProvider.GetRequiredService<ScopedProcessingService>();

           var rt = await scopedProcessingService.DoWork();
          return rt;
        }
    }

    public override async Task StopAsync(CancellationToken stoppingToken)
    {

        await base.StopAsync(stoppingToken);
    }
}`

bbenph avatar Sep 27 '21 07:09 bbenph