private async Task<WebSocketReceiveResult> ReceiveAsyncCore(ArraySegment<byte> buffer,
CancellationToken cancellationToken)
{
Debug.Assert(buffer != null);
if (NetEventSource.IsEnabled)
{
NetEventSource.Enter(this);
}
WebSocketReceiveResult receiveResult;
try
{
ThrowIfPendingException();
ThrowIfDisposed();
ThrowOnInvalidState(State, WebSocketState.Open, WebSocketState.CloseSent);
bool ownsCancellationTokenSource = false;
CancellationToken linkedCancellationToken = CancellationToken.None;
try
{
ownsCancellationTokenSource = _receiveOutstandingOperationHelper.TryStartOperation(cancellationToken,
out linkedCancellationToken);
if (!ownsCancellationTokenSource)
{
lock (_thisLock)
{
if (_closeAsyncStartedReceive)
{
throw new InvalidOperationException(
SR.Format(SR.net_WebSockets_ReceiveAsyncDisallowedAfterCloseAsync, nameof(CloseAsync), nameof(CloseOutputAsync)));
}
throw new InvalidOperationException(
SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, nameof(ReceiveAsync)));
}
}
EnsureReceiveOperation();
receiveResult = await _receiveOperation.Process(buffer, linkedCancellationToken).SuppressContextFlow();
if (NetEventSource.IsEnabled && receiveResult.Count > 0)
{
NetEventSource.DumpBuffer(this, buffer.Array, buffer.Offset, receiveResult.Count);
}
}
catch (Exception exception)
{
bool aborted = linkedCancellationToken.IsCancellationRequested;
Abort();
ThrowIfConvertibleException(nameof(ReceiveAsync), exception, cancellationToken, aborted);
throw;
}
finally
{
_receiveOutstandingOperationHelper.CompleteOperation(ownsCancellationTokenSource);
}
}
finally
{
if (NetEventSource.IsEnabled)
{
NetEventSource.Exit(this);
}
}
return receiveResult;
}