Task.Factory.FromAsync如何工作/表现?

时间:2011-10-16 13:31:45

标签: c# .net asynchronous task-parallel-library

我对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();  

感谢您的帮助,我真的很难配合异步编程。

1 个答案:

答案 0 :(得分:5)

FromAsync提供了一种方便的机制,使用Asynchronous Programming Model (APM)BeginXxxEndXxx方法创建Task

默认情况下,生成的Task将在线程池线程上执行(对SomeCode1()的后续调用将确实在当前线程上执行,与Task并行执行)。

ContinueWith上的Task方法确实更像是一个回调,即提供给此方法的委托将在任务完成后执行,也可以在某些线程上执行池线程。它阻止当前线程。

实际上,您应该在创建任务时设置此延续,例如

var task1 = Task<int>.Factory.FromAsync(Foo1, ...).ContinueWith(Foo2,...);

有关.NET中线程的更多一般和详细信息,我建议您阅读一篇好文章,例如CLR via C#的第五部分。