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

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

问题描述

我想知道在使用TPL TaskFactory.FromAsync 和使用 TaskFactory.StartNew 之间是否有任何性能影响阻塞版本的方法。我写一个TCP服务器,将支持不超过100个并发连接。在用第一个选项&链接多个读取&写操作与继续,我被留下丑陋,难以调试代码。

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.

我相信使用同步版本&然后用任务包装它将降低复杂性,

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 。区别在于,在 Stream Socket WebRequest ,你实际上最终会使用覆盖下的异步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上.NET SDK的这一部分,名为 TPL和传统.NET异步编程,了解有关如何合并这两种编程模型以实现异步nirvana的更多信息。

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 vs具有阻塞方法的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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