我正在使用websocket向1000个客户端发送消息。如果消息没有在100毫秒内发出,我想取消websocket.SendAsync。我的代码如下。
var cancelTaskToken = transport.GetTaskCancelToken();
cancelTaskToken.CancelAfter(100);
var webSocket = transport.GetWebSocket().WebSocket;
var webSocketContext = new WebSocketSendContext(webSocket, message.Value, transport, Counters, _trace);
var context = (WebSocketSendContext)webSocketContext;
try
{
if (context.socket.State != System.Net.WebSockets.WebSocketState.Open) return;
await context.socket.SendAsync(context.payload, System.Net.WebSockets.WebSocketMessageType.Binary, true, cancelTaskToken.Token);
context.transport.MarkHeatBeat();
context.counters.MessagesSentToClientTotal.Increment();
context.counters.MessagesSentToClientPerSec.Increment();
}
catch (OperationCanceledException ex)
{
context.trace.Error(ex, "cancel socket sending on {connectionId}. websocket state: {webSocketState}", transport.ConnectionId, webSocket.State);
context.counters.ErrorsTransportPerSec.Increment();
context.counters.ErrorsTransportTotal.Increment();
context.counters.ErrorsAllPerSec.Increment();
context.counters.ErrorsAllTotal.Increment();
}
但是在我的测试中,sendAsync总是在1000毫秒后发生。我不知道为什么websocket没有拿起我的100ms设置?
答案 0 :(得分:0)
@SeanOB,你是对的。日志中的1秒间隙是内部的serilog日志记录。然后它不会取消我的CancelToken中的超时设置。
我现在可以确认取消确实发生在100毫秒之后。