如何取消HttpListenerContext.AcceptWebSocketAsync?

Den*_*kiy 10 .net c# http websocket

它没有取消令牌参数.HttpListenerContext也没有相关的(Begin/End)AcceptWebSocket方法.

Ron*_*ald 5

也许以下解决方案更适合您的情况,它基于本文

一旦取消令牌被触发,这将停止侦听,然后您就可以实现自定义逻辑来取消操作。在我的情况下,它足以打破循环,但它真的可以是你想要的任何东西。

    public void Stop()
    {
        this.Status = ServerStatus.Stopping;

        this.listener.Stop();
        this.cancellationTokenSource.Cancel();

        this.Status = ServerStatus.Stopped;
    }

    private async void ListenForConnections(CancellationToken cancellationToken)
    {
        try
        {
            while (this.Status == ServerStatus.Running)
            {
                var socketTask = this.listener.AcceptSocketAsync();

                var tcs = new TaskCompletionSource<bool>();
                using (cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
                {
                    if (socketTask != await Task.WhenAny(socketTask, tcs.Task).ConfigureAwait(false))
                        break;
                }

                var context = new TcpContext(socketTask.Result);

                this.OnConnectionReceived(context);
            }
        }
        catch (ObjectDisposedException)
        {
            // Closed
        }
    }
Run Code Online (Sandbox Code Playgroud)