Skip to content

MqttConnectionHandler race condition #2173

@xemed-ahope

Description

@xemed-ahope

The initial state of MqttConnectionHandler can result in a NullReferenceException in the time between generic host starup and "full" startup. In my test environment this occurs consistently. For a workaround, I explicitly pull and inject the dependencies by calling StartAsync after building and prior to starting the host.

A fix is included with all the other goodies in #2103 .

Per @xljiulang:

If you want to delay starting MqttnetServer, you should fix MqttConnectionHandler as follows:

    public MqttConnectionHandler(IMqttNetLogger logger)
    {
        _logger = logger;
    }
    public override async Task OnConnectedAsync(ConnectionContext connection)
    {
        var clientHandler = ClientHandler;
        if (clientHandler == null)
        {
            connection.Abort();
            _logger.Publish(MqttNetLogLevel.Warning, nameof(MqttConnectionHandler), $"{nameof(MqttServer)} has not been started yet.", null, null);
            return;
        }
        ...
}

Initially called out by @xljiulang in #2102 (comment)

Addendum: Modified to initialize logger by injection, consistent with the full changes in #2103

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions