Skip to content

Commit b9cf229

Browse files
authored
Merge pull request #72 from cdauphinee/cdauphinee-patch-1
Fixing NRE and race in Connect/Disconnect
2 parents e5c19f7 + d0eec86 commit b9cf229

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed

PusherClient/Connection.cs

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,14 @@ public Connection(IPusher pusher, string url)
3939

4040
internal Task<ConnectionState> Connect()
4141
{
42-
if (_connectionTaskComplete != null)
43-
return _connectionTaskComplete.Task;
42+
var completionSource = _connectionTaskComplete;
43+
if (completionSource != null)
44+
return completionSource.Task;
4445

45-
_connectionTaskComplete = new TaskCompletionSource<ConnectionState>();
46+
completionSource = new TaskCompletionSource<ConnectionState>();
47+
var existingCompletionSource = Interlocked.CompareExchange(ref _connectionTaskComplete, completionSource, null);
48+
if (existingCompletionSource != null)
49+
return existingCompletionSource.Task;
4650

4751
// TODO: Add 'connecting_in' event
4852
Pusher.Trace.TraceEvent(TraceEventType.Information, 0, $"Connecting to: {_url}");
@@ -63,15 +67,19 @@ internal Task<ConnectionState> Connect()
6367

6468
_websocket.Open();
6569

66-
return _connectionTaskComplete.Task;
70+
return completionSource.Task;
6771
}
6872

6973
internal Task<ConnectionState> Disconnect()
7074
{
71-
if (_disconnectionTaskComplete != null)
72-
return _disconnectionTaskComplete.Task;
75+
var completionSource = _disconnectionTaskComplete;
76+
if (completionSource != null)
77+
return completionSource.Task;
7378

74-
_disconnectionTaskComplete = new TaskCompletionSource<ConnectionState>();
79+
completionSource = new TaskCompletionSource<ConnectionState>();
80+
var existingCompletionSource = Interlocked.CompareExchange(ref _disconnectionTaskComplete, completionSource, null);
81+
if (existingCompletionSource != null)
82+
return existingCompletionSource.Task;
7583

7684
Pusher.Trace.TraceEvent(TraceEventType.Information, 0, $"Disconnecting from: {_url}");
7785

@@ -80,7 +88,7 @@ internal Task<ConnectionState> Disconnect()
8088
_allowReconnect = false;
8189
_websocket.Close();
8290

83-
return _disconnectionTaskComplete.Task;
91+
return completionSource.Task;
8492
}
8593

8694
internal async Task<bool> Send(string message)
@@ -259,4 +267,4 @@ private void RaiseError(PusherException error)
259267
_pusher.ErrorOccured(error);
260268
}
261269
}
262-
}
270+
}

0 commit comments

Comments
 (0)