gpt4 book ai didi

c# - ThreadPool 和带有 while(true) 循环的方法?

转载 作者:太空宇宙 更新时间:2023-11-03 21:32:00 24 4
gpt4 key购买 nike

ThreadPool 利用线程回收来获得比使用多个 Thread 类更佳的性能。但是,这如何适用于在 ThreadPool 内部使用 while 循环的处理方法?

例如,如果我们将 ThreadPool 中的线程应用于已连接到 TCP 服务器的客户端,则该客户端将需要一个 while 循环来不断检查传入数据。可以退出循环以断开客户端,但前提是服务器关闭或客户端要求断开连接。

如果是这样的话,那么当大量客户端连接时,线程池有什么帮助呢?无论哪种方式,如果客户端保持连接,则使用相同数量的内存。如果它们保持连接,则线程无法回收。如果是这样,那么在客户端断开连接并打开一个线程进行回收之前,线程池将无济于事。

另一方面,有人建议我使用 Network.BeginReceive 和 NetworkStream.EndReceive 异步方法来避免线程一起使用以节省 RAM 使用和 CPU 使用。这是真的还是假的?

最佳答案

Either way the same amount of memory is used if the clients stay connected.

到目前为止,这是真的。由您的应用决定它需要为每个客户端保留多少状态。

If they stay connected, then the threads cannot be recycled. If so, then ThreadPool would not help much until a client disconnects and opens up a thread to recycle.

这是不正确的,因为它假定这些线程执行的所有有趣操作都是同步的。这是一种简单的操作模式,实际上现实世界的代码是异步的:一个线程调用请求一个 Action ,然后可以自由地做其他事情。当一个结果作为该操作的结果可用时,一些寻找其他事情要做的线程将运行对结果起作用的代码。

On the other hand it was suggested to me to use the Network.BeginReceive and NetworkStream.EndReceive asynchronous methods to avoid threads all together to save RAM usage and CPU usage. Is this true or not?

如上所述,像这样的异步方法将允许您只使用少量工作线程来为可能非常多的客户端提供服务——但它本身不会帮助或损害内存情况。

关于c# - ThreadPool 和带有 while(true) 循环的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23689074/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com