首页 > 解决方案 > Asp Net Core中线程是如何复用的

问题描述

您好,我正在构建一个 tcp 服务器,我将在其中连接多个客户端,这些客户端将向服务器发送和接收数据。

我想知道框架是否没有创建1:1的 线程客户端比率但使用线程如何发生以下情况:

1 .如果在接受套接字后执行的方法中包含一个循环,分配的线程(由线程池)不会在客户端上下文中被阻塞吗?
2 .每个客户端的上下文存储在哪里?

在此处输入图像描述

PS在我的图片中,我不明白蓝色线程(由线程池提供以服务两个客户端)如何被重用。

下面的代码包含 Handler(包含所有连接)和Client(一个套接字包装器,具有基本的读/写功能)。

套接字处理程序

  class Handler
            {

                private Dictionary<string, Client> clients = new Dictionary<string, Client>();
                private object Lock = new object();

                public Handler()
                {

                }
                public async Task LoopAsync(WebSocketManager manager)
                {
                    WebSocket clientSocket = await manager.AcceptWebSocketAsync();
                    string clientID = Ext.MakeId();
                    using(Client newClient = Client.Create(clientSocket, clientID))
                    {
                        while (newClient.KeepAlive)
                        {
                            await newClient.ReceiveFromSocketAsync();
                        }

                    }


                }
                public  bool RemoveClient(string ID)
                {
                    bool removed = false;
                    lock (Lock)
                    {
                        if (this.clients.TryGetValue(ID, out Client client))
                        {
                            removed= this.clients.Remove(ID);
                        }
                    }
                    return removed;

                }

            }

套接字包装器

class Client:IDisposable
    {
        public static Client Create(WebSocket socket,string id)
        {
            return new Client(socket, id);
        }
        private readonly string ID;
        private const int BUFFER_SIZE = 100;


        private readonly byte[] Buffer;
        public bool KeepAlive { get; private set; }
        private readonly WebSocket socket;


        private Client(WebSocket socket,string ID)
        {
            this.socket = socket;
            this.ID = ID;
            this.Buffer = new byte[BUFFER_SIZE];
        }
        public async  Task<ReadOnlyMemory<byte>> ReceiveFromSocketAsync()
        {   
            WebSocketReceiveResult result = await this.socket.ReceiveAsync(this.Buffer, CancellationToken.None);
            this.KeepAlive = result.MessageType==WebSocketMessageType.Close?false:true;
            return this.Buffer.AsMemory();
        }

        public async Task SendToSocketAsync(string message)
        {
            ReadOnlyMemory<byte> memory = Encoding.UTF8.GetBytes(message);
            await this.socket.SendAsync(memory, WebSocketMessageType.Binary,true,CancellationToken.None);
        }

        public void Dispose()
        {
            this.socket.Dispose();
        }
    }

将注入应用程序的服务

class SocketService
    {
        Handler hander;
        public SocketService(Handler _handler)
        {
            this.hander = _handler;
        }
        RequestDelegate next;

        public async Task Invoke(HttpContext context)
        {
            if (!context.WebSockets.IsWebSocketRequest)
            {
                await  this.next(context);
                return;
            }
            await this.hander.AddClientAsync(context.WebSockets);

        }
    }

标签: asp.net-coretcpwebsocketc#-7.3

解决方案


推荐阅读