TPL TaskFactory.FromAsync 与具有阻塞方法的任务 [英] TPL TaskFactory.FromAsync vs Tasks with blocking methods

查看:17
本文介绍了TPL TaskFactory.FromAsync 与具有阻塞方法的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在方法的阻塞版本上使用 TPL TaskFactory.FromAsync 和使用 TaskFactory.StartNew 之间是否有任何性能影响.我正在编写一个支持不超过 100 个并发连接的 TCP 服务器.使用第一个选项编写代码后 &链接多个读&用 continue with 写操作,我留下了难看的、难以调试的代码.

I was wondering if there were any performance implications between using TPL TaskFactory.FromAsync and using TaskFactory.StartNew on blocking versions of the methods. I'm writing a TCP server that will support no more than 100 concurrent connections. After writing code with the first option & chaining multiple read & write operations with continue with, I was left with ugly, hard to debug code.

我相信用同步版本编写代码 &然后用 Task 包装它会降低复杂性 &提高可测试性,但我担心这样做对性能的影响.

I believe writing code with the synchronous version & then wrapping it with a Task would decrease complexity & increase testability, but I'm worried about the performance implications of doing this.

例如,这两个调用之间是否存在性能差异:

For example, are there any performance differences between these 2 calls:

NetworkStream stream;
byte[] data;
int bytesRead;

//using FromAsync
Task<int> readChunk = Task<int>.Factory.FromAsync (
      stream.BeginRead, stream.EndRead,
      data, bytesRead, data.Length - bytesRead, null);

//using StartNew with blocking version
Task<int> readChunk2 = Task<int>.Factory.StartNew(() => 
      stream.Read(data, bytesRead, data.Length - bytesRead));

推荐答案

当 API 提供方法的 BeginXXX/EndXXX 版本时,您绝对希望使用 FromAsync.不同之处在于,在诸如 StreamSocketWebRequest 之类的情况下,您实际上最终会在下面使用异步 I/O封面(例如 Windows 上的 I/O 完成端口)比阻塞多个 CPU 线程执行同步操作更有效.这些方法提供了实现 I/O 可扩展性的最佳方式.

You absolutely want to use FromAsync when an API offers a BeginXXX/EndXXX version of a method. The difference is that, in the case of something like Stream or Socket or WebRequest, you'll actually end up using async I/O underneath the covers (e.g. I/O Completion Ports on Windows) which is far more efficient than blocking multiple CPU threads doing a synchronous operation. These methods provide the best way to achieve I/O scalability.

查看 MSDN 上题为 TPL 和传统 .NET 异步编程 有关如何结合这两种编程模型以实现异步必杀技的更多信息.

Check out this section of the .NET SDK on MSDN entitled TPL and Traditional .NET Asynchronous Programming for more information on how to combine these two programming models to achieve async nirvana.

这篇关于TPL TaskFactory.FromAsync 与具有阻塞方法的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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