asp.net-core - 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);
}
}
解决方案
推荐阅读
- c# - Dynamics CRM QueryExpression 嵌套的 LinkedEntity
- php - Union 2表sql,只显示第一个查询
- r - 如何在旧的、不兼容的 R 版本上安装新的 R 包
- preact - 如何将 Preact 网站嵌入到现有网站中?
- xamarin.forms - 网格与 iOS 中的 ListView 重叠 - XamarinForms
- python - Dask:使用典型的 numpy 索引更新 dask 数组中的值时出现赋值错误
- c# - 我将 ulong 用于 100 的阶乘,但它仍然溢出
- python - Selenium 测试是否存在 CSS 类
- ios - UIImagePickerController 不压缩视频
- javascript - 尝试通过 Google App Scripts 将表单条目(从侧边栏)传递到 Google 表格中的特定列/单元格