我使用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或保持活动消息,这可能是问题所在。
我用这个库进行负载测试,所以我创建了很多连接,发送了很多消息,它就工作了。它不太好,但它有效。