我正在使用SendAsync方法在循环中发送1000条消息,并在此代码行中获取以下异常

await _ws.SendAsync(new ArraySegment<byte>(messageBuffer, offset, count), WebSocketMessageType.Text, lastMessage, _cancellationToken);


我究竟做错了什么?我知道某个地方一定是瓶颈,因为两次发送之间我没有睡眠。我可以等待某个状态来证明以下异常吗?

System.InvalidOperationException was unhandled by user code
  HResult=-2146233079
  Message=There is already one outstanding 'SendAsync' call for this WebSocket instance. ReceiveAsync and SendAsync can be called simultaneously, but at most one outstanding operation for each of them is allowed at the same time.
  Source=System
  StackTrace:
       at System.Net.WebSockets.WebSocketBase.<SendAsyncCore>d__8.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
       at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
       at zzz.Stub.WebSocketWrapper.<SendMessageAsync>d__0.MoveNext() in zzz

最佳答案

请记住,您不能并行发送或接收。既然您正在等待,这似乎很好。

如果您有其他线程发送ping或保持活动消息,则可能是问题所在。

我使用该库进行负载测试,因此我创建了许多连接并发送了许多消息,并且可以正常工作。这不是很好,但是可以。

09-04 15:11