我想知道在使用TPL TaskFactory.FromAsync
和TaskFactory.StartNew
在阻塞方法上的性能影响是否有所不同。我正在编写一个TCP服务器,最多支持100个并发连接。使用第一种选项,并将多个读取和写入操作链接起来后,我得到了难以调试的代码。
我相信使用同步版本的代码,并用任务(Task)包装它会降低复杂性并增加可测试性,但我担心这样做会带来性能方面的影响。
例如,这两个调用之间是否存在性能差异:
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));