我想知道在使用TPL TaskFactory.FromAsync和使用TaskFactory.StartNew阻塞版本的方法之间是否存在性能影响.我正在编写一个TCP服务器,它将支持不超过100个并发连接.在使用第一个选项编写代码并使用continue来链接多个读写操作之后,我留下了丑陋,难以调试的代码.
我相信用同步版本编写代码然后用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));
Run Code Online (Sandbox Code Playgroud) 我对C#比较新,所以请耐心等待.
我试图了解Task FromAsync的工作原理.
var task1 = Task<int>.Factory.FromAsync(Foo1, ...); //what happens here? Is this
called on a thread from threadpool?
SomeCode1(); // <- is this code executed in parallel with Foo1
task1.ContinueWith(Foo2,...); //does this block the current thread until Foo1
finishes? Shouldn't it act like a callback? If this whole code runs on a "normal"
thread does it block it? If this runs on a thread from a thread pool does it
release the thread until Foo1 finishes?
SomeCode2();
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助,我真的在努力学习异步编程.