StackExchange/StackExchange.Redis — pull request #113 by PashaPash (2014-10-26 16:29:53+00:00)
Title: Fixed race condition in PhysicalConnection creation

There was a race condition in `PhysicalBridge.GetConnection()` method:

physical = new PhysicalConnection(this);

- `PhysicalConnection` constructor starts connection initialization in async manner, by `multiplexer.SocketManager.BeginConnect -> socket.BeginConnect` call.
- `socket.BeginConnect` completes synchronously (or asynchronously, but still before originating thread will return from `PhysicalConnection` ctor).
- `EndConnectImpl` calls `PhysicalConnection.Connected`
- `PhysicalConnection.Connected` reports state change by calling `this.bridge.OnConnected`
- bridge.OnConnected fails 'physical == connection' check as control is still in `new PhysicalConnection` and `bridge.physical` is not assigned yet.
- bridge disposes the connection.

Control finally returns up to the stack, to `PhysicalConnection` ctor, then to `physical =` assignment, but connection is already killed.

If server is fast enough (local or really fast server in the same DC) then `socket.BeginConnect` is likely to always complete sync, causing permanent connection failure (could be reproduced by moving code from `PhysicalConnection.BeginConnect` back to ctor and running the `ConnectsWhenBeginConnectCompletesSynchronously` test.

Sorry, had to add some debugging stuff - found no way to force sync socket.BeginConnect using standard flags.