Skip to content
Open
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 32 additions & 13 deletions SteamKit2/SteamKit2/Networking/Steam3/WebSocketContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@ public WebSocketContext(WebSocketConnection connection, EndPoint endPoint)

cts = new CancellationTokenSource();
socket = new ClientWebSocket();
semaphore = new SemaphoreSlim( 1, 1 );
connectionUri = ConstructUri(endPoint);
}

readonly WebSocketConnection connection;
readonly CancellationTokenSource cts;
readonly ClientWebSocket socket;
readonly SemaphoreSlim semaphore;
readonly Uri connectionUri;
Task? runloopTask;
int disposed;
Expand Down Expand Up @@ -87,18 +89,27 @@ async Task RunCore(HttpMessageInvoker invoker, TimeSpan connectionTimeout, Cance
}
}

if (socket.State == WebSocketState.Open)
await semaphore.WaitAsync().ConfigureAwait( false );

try
{
connection.log.LogDebug( nameof(WebSocketContext), "Closing connection...");
try
{
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, default).ConfigureAwait(false);
}
catch (Win32Exception ex)
if (!cancellationToken.IsCancellationRequested && socket.State == WebSocketState.Open)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will socket.Dispose close cleanly, or should it still let CloseAsync be called here?

{
connection.log.LogDebug( nameof(WebSocketContext), "Error closing connection: {0}", ex.Message);
connection.log.LogDebug( nameof(WebSocketContext), "Closing connection...");
try
{
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, default).ConfigureAwait(false);
}
catch (Win32Exception ex)
{
connection.log.LogDebug( nameof(WebSocketContext), "Error closing connection: {0}", ex.Message);
}
}
}
finally
{
semaphore.Release();
}
}

public async Task SendAsync(Memory<byte> data)
Expand All @@ -117,16 +128,24 @@ public async Task SendAsync(Memory<byte> data)

public void Dispose()
{
if (Interlocked.Exchange(ref disposed, 1) == 1)
if ( Interlocked.Exchange( ref disposed, 1 ) == 1 )
{
return;
}

cts.Cancel();
cts.Dispose();
runloopTask = null;
semaphore.Wait();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wouldn't mind an explanatory comment here as to what flow is happening in regards to the semaphore and the cancellation.

try
{
cts.Cancel();
cts.Dispose();
runloopTask = null;

socket.Dispose();
socket.Dispose();
}
finally
{
semaphore.Release();
}
}

async Task<byte[]?> ReadMessageAsync( CancellationToken cancellationToken )
Expand Down