MqttClient 生命周期应该如何管理?

问题描述 投票:0回答:0

我继承了一个使用

ManagedMqttClient
的应用程序,并在与代理断开连接时替换/处置该客户端。

public async Task<bool> CreateManagedClient()
{
    try
    {
        if (_mqttClient != null)
            _mqttClient.Dispose();

        _factory = new MqttFactory();
        _mqttClient = _factory.CreateManagedMqttClient();
        await Task.Delay(System.TimeSpan.FromSeconds(2));
    }
    catch (Exception e)
    {
        _logger.Log("...", LogMessageCodes.Error);
        _mqttClient.Dispose();
        _mqttClient = null;
        return false;
    }
    return true;
}

显然,这里存在线程安全问题。还有其他线程正在使用此客户端接收我们

PublishAsync
的数据,如果我们的另一个服务出现故障,这些线程将与代理断开连接。所以,各种情况都产生了
ObjectDisposed
例外。

那么,有两个问题:

  1. 我们应该使用
    ManagedMqttClient
    吗?这个线程听起来好像
    MqttClient
    是首选。
  2. 在多线程环境中管理客户端生命周期的规范方法是什么?(假设我们要正确处置客户端。)

我尝试在应用程序的生命周期中使用单个客户端(只需调用

StopAsync/StartAsync
),但遇到“托管客户端已启动”异常。而且,考虑到有一个制造客户的工厂,这感觉就像是黑客攻击。

您不能

lock
围绕异步调用。我也在考虑使用
SemaphoreSlim

c# thread-safety mqttnet
© www.soinside.com 2019 - 2024. All rights reserved.