任务中的异步套接字操作 [英] Asynchronous socket operations in a Task

查看:84
本文介绍了任务中的异步套接字操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Threading.Tasks.Task,它处理许多客户端套接字操作(连接,接收和发送).

I have a Threading.Tasks.Task that handles a number of client socket operations (connecting, receiving and sending).

我知道,最好在Await中使用非阻塞方法,因为否则我将遇到驻留线程等待其响应"的情况.但是,尽管Socket类具有异步方法(SendAsync等),它们与通常的Task Parallel Library异步方法并不相同,但它们不返回Task,因此无法等待.

I understand that where possible it's best to use non blocking methods using Await because otherwise I'll end up with "parked threads waiting for their response". However, while the Socket class has async methods (SendAsync and so on) they aren't the same as the usual Task Parallel Library async methods, they don't return a Task and cannot be awaited.

我意识到我可以使用TaskCompletionSource包装这些套接字异步方法,但是这样做有什么好处,还是最终还是会保留线程?

I realise that I can wrap these socket async methods with a TaskCompletionSource but is there any benefit to doing so or will it ultimately still be parking the thread?

推荐答案

如Servy所述.只要您正确使用异步模式,使用 TaskCompletionSource 本身就不会创建(或驻留)任何线程.

As Servy explained. Using TaskCompletionSource as in of itself doesn't create (or park) any threads as long as you're using the asynchronous pattern correctly.

.Net框架中有3种不同的异步模式:

There are 3 different asynchronous patterns in the .Net framework:

  1. 异步编程模型(APM).
  2. 基于事件的异步模式(EAP).
  3. 基于任务的异步模式(TAP).

您要实现的目标是将一种模式EAP转换"为另一种模式TAP.一个更简单的解决方案是使用.Net内置的从APM模式到TAP的转换",

What you're trying to achieve is "convert" one pattern, the EAP, to another one, TAP. A simpler solution would be to use .Net's built-in "conversion" from the APM pattern to TAP, Task.Factory.FromAsync (which internally uses TaskCompletionSource):

socket.BeginConnect(host, port, asyncResult =>
{
    socket.EndConnect(asyncResult);
    Console.WriteLine("Socket connected");
}, null);

TAP

await Task.Factory.FromAsync(socket.BeginConnect, socket.EndConnect, host, port, null);
Console.WriteLine("Socket connected");

这篇关于任务中的异步套接字操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆