是否应该异步执行对 NetworkStream 的写入

发布于 2024-11-04 03:19:48 字数 411 浏览 1 评论 0原文

鉴于 NetworkStream.Write() 是一个阻塞调用,应该像 SendMessage() 这样的方法创建一个新线程来执行写入操作,或者应该使用 SendMessage() 方法阻塞直到消息发送或者发生异常?

我的直觉告诉我阻止此方法是合理的,但查看 C# 中套接字的非常好的示例 我发现他们正在创建一个新线程。我发现创建另一个线程的主要问题是错误处理。

PS:我知道 Write、Read 等的异步版本,但发现 IAsyncResult 相当混乱,目前暂缓使用这些选项。

Given that NetworkStream.Write() is a blocking call should a method like SendMessage() create a new thread to perform the write operation or should the SendMessage() method block until the message is sent or an exception occurs?

My gut tells me it is reasonable to block this method but looking at a really nice example of sockets in C# I am finding they are creating a new thread. The main issue I see with creating another thread is error handling.

PS: I am aware of the Async versions of Write, Read and so forth but find IAsyncResult rather confusing and am currently holding off on using those options.

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

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

发布评论

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

评论(2

弄潮 2024-11-11 03:19:48

如果您在 UI 线程上调用 SendMessage(),那么它将阻止它,并且您的应用程序将“冻结”。使用 ThreadPool.QueueUserItem(o => SendMessage()) 或 Task.Factory.StartNew(() => SendMessage,而不是每次要发送数据时创建一个新线程()) 来自 .NET 4.0 中的任务并行库

如果您的应用程序正在为客户端提供服务,并且您为每个客户端创建一个新线程,那么如果您不想在将数据发送到客户端时执行其他工作,则 SendMessage() 可能会阻塞。

为每个客户端创建一个新线程有一个缺点:大量线程将消耗大量资源,并且大多数时候这些线程将处于空闲状态,同时它们可以为其他客户端提供服务。如果您希望创建高性能服务器应用程序,您应该学习异步编程。

请查看异步 CTP。它可以让你编写看起来像同步代码的异步代码,而没有混乱的回调。

public async void SendMessage()
{
    try {
        await socket.WriteAsync(buffer, 0, buffer.Length);
    } catch (...) {
        // handle it
   }
}

现在 SendMessage() 不会阻塞,因为它将异步执行,而且看起来一点也不可怕!

If you are calling SendMessage() on a UI thread then it will block it and your application will "freeze". Instead of creating a new thread each time you want to send data, use ThreadPool.QueueUserItem(o => SendMessage()) or Task.Factory.StartNew(() => SendMessage()) from Task Parallel Library in .NET 4.0

If your application is servicing clients and you create a new thread for each client, then SendMessage() can block if you don't want to do other work while sending the data to the client.

Creating a new thread for each client has one drawback: lots of threads will consume a lot of resources and most of the time these threads will be idling while they could be servicing other clients in the meantime. If you wish to create a high performance server application you should learn about asynchronous programming.

Check out Async CTP. It will let you write asynchronous code that looks like synchronous code without messy callbacks

public async void SendMessage()
{
    try {
        await socket.WriteAsync(buffer, 0, buffer.Length);
    } catch (...) {
        // handle it
   }
}

Now SendMessage() won't block because it will be executed asynchronously and it does not look scary at all!

浪漫之都 2024-11-11 03:19:48

我强烈建议您查看任务并行库

您可以从当前 .net 中的任何异步模式创建任务。

任务将在线程池上执行,异常将从其他线程中妥善整理。

I strongly recommend you to take a look at the Task Parallel Library.

You can create Task from any async pattern in current .net.

Task will be executed on the thread pool, and exceptions will be marshaled kindly from other threads.

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