Skip to content

Commit

Permalink
Merge pull request #824 from dotnet/fix823
Browse files Browse the repository at this point in the history
Override `WebSocketStream` APM style async methods
  • Loading branch information
AArnott authored Jan 20, 2025
2 parents bb528c9 + b63e619 commit 907f49a
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/Nerdbank.Streams/WebSocketStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ namespace Nerdbank.Streams
using System.Threading;
using System.Threading.Tasks;
using Microsoft;
using Microsoft.VisualStudio.Threading;

/// <summary>
/// Exposes a <see cref="WebSocket"/> as a <see cref="Stream"/>.
Expand Down Expand Up @@ -98,7 +99,21 @@ public override Task WriteAsync(byte[] buffer, int offset, int count, Cancellati
return this.webSocket.SendAsync(new ArraySegment<byte>(buffer, offset, count), WebSocketMessageType.Binary, true, cancellationToken);
}

#pragma warning disable VSTHRD002 // Avoid problematic synchronous waits
/// <inheritdoc />
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
=> this.ReadAsync(buffer, offset, count, CancellationToken.None).ToApm(callback, state);

/// <inheritdoc />
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
=> this.WriteAsync(buffer, offset, count, CancellationToken.None).ToApm(callback, state);

#pragma warning disable VSTHRD002 // Avoid problematic synchronous waits - This should not deadlock because the implementation always uses .ConfigureAwait(false).
/// <inheritdoc />
public override int EndRead(IAsyncResult asyncResult)
=> ((Task<int>)asyncResult).GetAwaiter().GetResult();

public override void EndWrite(IAsyncResult asyncResult)
=> ((Task)asyncResult).GetAwaiter().GetResult();

/// <inheritdoc />
public override int Read(byte[] buffer, int offset, int count) => this.ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
Expand Down

0 comments on commit 907f49a

Please sign in to comment.