An alternative to #833

This is an alternative to #833. It fixes the race condition by synchronizing the message dispatch to the client code. @motus: Can you test this, please?