【问题标题】:Is it safe to await a Task in OnNext() method of an Observer?在观察者的 OnNext() 方法中等待任务是否安全?
【发布时间】:2018-08-20 15:36:56
【问题描述】:

我创建了一个自定义观察者,它基本上在其 OnNext() 方法中执行一个异步任务。

我想知道这样做是否是个好主意,因为要记住 async void 不是 great。

public class MessageObserver : IObserver<Message>
{
    private IDisposable _unsubscriber;
    private readonly IQueueClient _client;
    private readonly TelemetryClient _telemetryClient;

    public MessageObserver(IQueueClient client, TelemetryClient telemetryClient)
    {
        _client = client;
        _telemetryClient = telemetryClient;
    }

    public virtual void Subscribe(IObservable<Message> provider)
    {
        _unsubscriber = provider.Subscribe(this);
    }

    public virtual void Unsubscribe()
    {
        _unsubscriber.Dispose();
    }

    public virtual void OnCompleted()
    {
    }

    public virtual void OnError(Exception error)
    {
    }

    public virtual async void OnNext(Message message)
    {
        try
        {
            await _client.SendAsync(message);
        }
        catch (Exception ex)
        {
            _telemetryClient.TrackException(ex);
        }
    }
}

编辑/添加代码

我有一个 API,我从 Angular 客户端向其发布资源,一旦资源被记录到数据库中,我会立即向 Azure 服务总线发送一条消息,然后返回之前记录的实体。

我不想在返回客户端之前等待 Azure 服务总线消息发送完毕,所以我想通知 Rx 观察者我有一条新消息需要在其他线程上异步处理。

这是我的结构:

    // POST: /api/management/campaign
    [HttpPost]
    public async Task<IActionResult> Create([FromBody] CampaignViewModel model)
    {
        try
        {
            if (ModelState.IsValid)
            {
                var createdCampaign = await _campaignService.CreateCampaign(Mapping.ToCampaign(model));
                _upsertServiceBus.SendMessage(new Message(Encoding.UTF8.GetBytes(createdCampaign.CampaignId.ToString())));
                return Ok(Mapping.ToCampaignViewModel(createdCampaign));
            }

            return BadRequest(ModelState);
        }
        catch (Exception ex)
        {
            _telemetryClient.TrackException(ex);
            return BadRequest(new OpenIdConnectResponse
            {
                Error = OpenIdConnectConstants.Errors.InvalidRequest,
                ErrorDescription = Constants.GenericError
            });
        }
    }

-

    public class BusService : IBusService
    {
        private readonly IObservable<Message> _messageObservable;
        private readonly ICollection<Message> _messages = new Collection<Message>();
        private readonly IQueueClient _queueClient;
        private readonly MessageObserver _messageObserver;
        private readonly TelemetryClient _telemetryClient;

        protected BusService(IConfiguration configuration, string queueName, TelemetryClient telemetryClient)
        {
            _telemetryClient = telemetryClient;
            _queueClient = new QueueClient(configuration["ServiceBusConnectionString"], queueName);
            _messageObservable = _messages.ToObservable();
            _messageObserver = new MessageObserver(_queueClient, _telemetryClient);
            _messageObserver.Subscribe(_messageObservable);
        }

        public void SendMessage(Message message)
        {
            _messageObserver.OnNext(message);
        }
    }

在@Shlomo 的回答的帮助下编辑/解决方案:

public class BusService : IBusService
{
    private readonly IQueueClient _queueClient;
    private readonly TelemetryClient _telemetryClient;
    private readonly Subject<Message> _subject = new Subject<Message>();

    protected BusService(IConfiguration configuration, string queueName, TelemetryClient telemetryClient)
    {
        _telemetryClient = telemetryClient;
        _queueClient = new QueueClient(configuration["ServiceBusConnectionString"], queueName);
        _subject
            .ObserveOn(TaskPoolScheduler.Default)
            .SelectMany(message =>
            {
                return Observable.FromAsync(() =>
                {
                    var waitAndRetryPolicy = Policy
                        .Handle<Exception>()
                        .WaitAndRetryAsync(3, retryAttempt =>
                                TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)),
                            (exception, retryCount, context) =>
                            {
                                _telemetryClient.TrackEvent(
                                    $"Sending message to Azure Service Bus failed with exception ${exception.Message}. Retrying...");
                            }
                        );

                    return waitAndRetryPolicy.ExecuteAsync(async ct =>
                    {
                        _telemetryClient.TrackEvent("Sending message to Azure Service Bus...");
                        await _queueClient.SendAsync(message);
                    }, CancellationToken.None);
                });
            })
            .Subscribe(unit => { _telemetryClient.TrackEvent("Message sent to Azure Service Bus."); },
                ex => _telemetryClient.TrackException(ex));
    }

    public void SendMessage(Message message)
    {
        _subject.OnNext(message);
    }
}

【问题讨论】:

  • 没有。这不是一个好主意。 async void 是个坏主意,就像实现自己的观察者一样。无论你想做什么,我都很肯定有更好的方法来做到这一点。我建议您发布您想要实现的目标。
  • 我已经相应地更新了我的主题。

标签: .net reactive-programming system.reactive reactive rx.net


【解决方案1】:

我无法复制或测试,但希望这可以帮助您入门。

此解决方案将_messages、_messageObserver 和_messageObservable 替换为主题和响应式查询。几个注意事项:

  • ObserveOn 允许您通过更改“调度程序”来转移线程。我选择了TaskPoolScheduler,它将在不同的任务上执行其余的查询。
  • 我建议调用_queueClient.SendAsync 的同步版本,因为此示例允许 Rx 处理线程。
  • 此解决方案使用 Rx 异常处理,这将在发生异常时终止可观察/处理。如果您希望它自动重启,请添加.Catch/.Retry。

代码:

public class BusService : IBusService
{
    private readonly IQueueClient _queueClient;
    private readonly TelemetryClient _telemetryClient;
    private readonly Subject<Message> _subject = new Subject<Message>();

    protected BusService(IConfiguration configuration, string queueName, TelemetryClient telemetryClient)
    {
        _telemetryClient = telemetryClient;
        _queueClient = new QueueClient(configuration["ServiceBusConnectionString"], queueName);
        _subject
            .ObserveOn(TaskPoolScheduler.Default)  // handle on an available task
            .Select(msg => _queueClient.Send(msg)) // syncronous, not async, because already on a different task
            .Subscribe(result => { /* log normal result */}, ex => _telemetryClient.TrackException(e), () => {});
    }

    public void SendMessage(Message message)
    {
        _subject.OnNext(message);
    }
}

正如我所提到的,代码使用Subject,您会发现这里有很多问答,不推荐它们。如果需要,您可以将主题替换为事件和坐在该事件上的可观察对象。主题更容易展示,而且我认为最好保持私密。

【讨论】:

  • 看起来不错,谢谢!所以我正在考虑调用 _queueClient.SendAsync(msg).Wait();因为没有来自 QueueClient 的同步方法调用。但我明白了,非常感谢。
  • 我已更新主题以包含解决方案,还涉及 Polly 重试策略。再次感谢。
猜你喜欢
  • 2019-06-05
  • 1970-01-01
  • 2019-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-12
  • 2010-10-16
相关资源
最近更新 更多