/// <summary> /// Receives data on <see cref="T:WebAssembly.Net.WebSockets.ClientWebSocket"/> as an asynchronous operation. /// </summary> /// <returns>The async.</returns> /// <param name="buffer">Buffer.</param> /// <param name="cancellationToken">Cancellation token.</param> public override async Task <WebSocketReceiveResult> ReceiveAsync(ArraySegment <byte> buffer, CancellationToken cancellationToken) { ThrowIfDisposed(); ThrowOnInvalidState(State, WebSocketState.Open, WebSocketState.CloseSent); var tcsReceive = new TaskCompletionSource <WebSocketReceiveResult> (); // Wrap the cancellationToken in a using so that it can be disposed of whether // we successfully receive or not. // Otherwise any timeout/cancellation would apply to the full session. using (cancellationToken.Register(() => tcsReceive.TrySetCanceled())) { if (bufferedPayload == null) { bufferedPayload = await receiveMessageQueue.DequeuePayloadAsync(cancellationToken); } try { var endOfMessage = bufferedPayload.BufferPayload(buffer, out WebSocketReceiveResult receiveResult); tcsReceive.SetResult(receiveResult); if (endOfMessage) { bufferedPayload = null; } } catch (Exception exc) { throw new WebSocketException(WebSocketError.NativeError, exc); } return(await tcsReceive.Task); } }