How does Task.Factory.FromAsync work / behave?

2019-05-07 00:32发布

I'm relatively new to C#, so please bear with me.

I am trying to understand how Task FromAsync works.

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

Thank you for your help, I'm really struggling with async programming.

1条回答
太酷不给撩
2楼-- · 2019-05-07 01:10

FromAsync provides a convenient mechanism which uses the BeginXxx and EndXxx methods of the Asynchronous Programming Model (APM) to create a Task.

The resulting Task will, by default, be executed on a thread pool thread (and your subsequent call to SomeCode1() will indeed execute on the current thread, in parallel to the Task).

The ContinueWith method on Task does indeed act rather like a callback, i.e. the delegate provided to this method will execute after the task has finished, also on some thread pool thread. It does not block the current thread.

Indeed, you should set up this continuation when creating the task, e.g.

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

For more general and detailed info on threading in .NET I thoroughly recommend reading a good text such as part V of CLR via C#.

查看更多
登录 后发表回答