如果已经在单独的线程上,是否有必要使用异步 Begin/End 方法?

发布于 2024-12-05 12:56:47 字数 1876 浏览 1 评论 0 原文

试图弄清楚我是否应该使用异步方法,例如:

而不是其同步 TcpListener.AcceptTcpClientNetworkStream.Read 版本。我一直在查看相关线程,但我仍然对一件事有点不确定:

问题: 使用异步方法的主要优点是 GUI 不会被锁定。但是,这些方法将在单独的任务 线程本身,因此不存在这种威胁。此外,TcpListener.AcceptTcpClient 会阻塞线程,直到建立连接,这样就不会浪费 CPU 周期。既然是这样,那么为什么这么多人总是推荐使用异步版本呢?在这种情况下,同步版本似乎会更好?

此外,使用异步方法的另一个缺点是增加了复杂性和对象的不断转换。例如,必须这样做:

private void SomeMethod()
{
    // ...

    listener.BeginAcceptTcpClient(OnAcceptConnection, listener);
}

private void OnAcceptConnection(IAsyncResult asyn)
{
    TcpListener listener = (TcpListener)asyn.AsyncState;

    TcpClient client = listener.EndAcceptTcpClient(asyn);
}

与此相反:

TcpClient client = Listener.AcceptTcpClient();

另外,由于必须创建另一个线程,异步版本似乎会产生更多开销。 (基本上,每个连接都会有一个线程,然后在读取该线程时也会有另一个线程。Threadception!)

此外,还存在 TcpListener 的装箱和拆箱以及与创建、管理和关闭这些附加线程相关的开销。

基本上,通常只有单独的线程来处理单独的客户端连接,现在有了这样的线程,然后为执行的每种类型的操作(读取/写入流数据并侦听服务器端的新连接)提供了一个附加线程,

请纠正我如果我错了。我对线程还是新手,我正在尝试理解这一切。但是,在这种情况下,似乎使用普通的同步方法并且仅阻塞线程就是最佳解决方案?

Trying to figure out whether or not I should use async methods or not such as:

and

as opposed to their synchronous TcpListener.AcceptTcpClient and NetworkStream.Read versions. I've been looking at related threads but I'm still a bit unsure about one thing:

Question: The main advantage of using an asynchronous method is that the GUI is not locked up. However, these methods will be called on separate Task threads as it is so there is no threat of that. Also, TcpListener.AcceptTcpClient blocks the thread until a connection is made so there is no wasted CPU cycles. Since this is the case, then why do so many always recommend using the async versions? It seems like in this case the synchronous versions would be superior?

Also, another disadvantage of using asynchronous methods is the increased complexity and constant casting of objects. For example, having to do this:

private void SomeMethod()
{
    // ...

    listener.BeginAcceptTcpClient(OnAcceptConnection, listener);
}

private void OnAcceptConnection(IAsyncResult asyn)
{
    TcpListener listener = (TcpListener)asyn.AsyncState;

    TcpClient client = listener.EndAcceptTcpClient(asyn);
}

As opposed to this:

TcpClient client = listener.AcceptTcpClient();

Also it seems like the async versions would have much more overhead due to having to create another thread. (Basically, every connection would have a thread and then when reading that thread would also have another thread. Threadception!)

Also, there is the boxing and unboxing of the TcpListener and the overhead associated with creating, managing, and closing these additional threads.

Basically, where normally there would just be individual threads for handling individual client connections, now there is that and then an additional thread for each type of operation performed (reading/writing stream data and listening for new connections on the server's end)

Please correct me if I am wrong. I am still new to threading and I'm trying to understand this all. However, in this case it seems like using the normal synchronous methods and just blocking the thread would be the optimal solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浪推晚风 2024-12-12 12:56:47

TcpListener.AcceptTcpClient 会阻塞线程,直到建立连接,这样就不会浪费 CPU 周期。

但也没有任何工作完成。线程是一个非常昂贵的操作系统对象,几乎是最昂贵的。当线程因连接请求而阻塞时,您的程序正在消耗一兆字节的内存而未使用它。

但是,这些方法将在单独的任务线程上调用,因此不存在这种威胁

任务也不是一个好的解决方案的威胁,它使用线程池线程,但线程会阻塞。线程池管理器尝试保持正在运行的 TP 线程数等于机器上的 cpu 核心数。当 TP 线程长时间阻塞时,这将无法正常工作。它阻止其他等待轮到的 TP 线程完成其他有用的工作。

BeginAcceptTcpClient() 使用所谓的 I/O 完成回调。套接字侦听时不会消耗任何系统资源。一旦有连接请求到来,操作系统就会运行 APC(异步过程调用),它会获取线程池线程来进行回调。线程本身的使用时间通常为几微秒。非常高效。

在下一版本的 C# 中,使用下一个 asyncawait 关键字,此类代码将变得更加简单。年底吧,也许吧。

TcpListener.AcceptTcpClient blocks the thread until a connection is made so there is no wasted CPU cycles.

But there is also no work getting done. A Thread is a very expensive operating system object, about the most expensive there is. Your program is consuming a megabyte of memory without it being used while the thread blocks on connection request.

However, these methods will be called on separate Task threads as it is so there is no threat of that

A Task is not a good solution either, it uses a threadpool thread but the thread will block. The threadpool manager tries to keep the number of running TP threads equal to the number of cpu cores on the machine. That won't work well when a TP thread blocks for a long time. It prevents other useful work from being done by other TP threads that are waiting to get their turn.

BeginAcceptTcpClient() uses a so-called I/O completion callback. No system resources are consumed while the socket is listening. As soon as a connection request comes in, the operating system runs an APC (asynchronous procedure call) which grabs a threadpool thread to make the callback. The thread itself is in use for, typically, a few microseconds. Very efficient.

This kind of code will get a lot simpler in the next version of C# with the next async and await keywords. End of the year, maybe.

心作怪 2024-12-12 12:56:47

如果您在任何线程上调用AcceptTcpClient(),则在获得连接之前该线程将毫无用处。

如果调用BeginAcceptTcpClient(),调用线程可以立即停止,而不会浪费线程。

这在使用 ThreadPool(或 TPL)时尤其重要,因为它们使用有限数量的池线程。
如果有太多线程等待操作,则可能会耗尽线程池线程,因此新工作项必须等待其他线程之一完成。

If you call AcceptTcpClient() on any thread, that thread is useless until you get a connection.

If you call BeginAcceptTcpClient(), the calling thread can stop immediately, without wasting the thread.

This is particularly important when using the ThreadPool (or the TPL), since they use a limited number of pool threads.
If you have too many threads waiting for operations, you can run out of threadpool threads, so that new work items will have to wait until one of the other threads finish.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文