如何Task.Factory.FromAsync工作/行为?行为、工作、Task、Factory

2023-09-05 01:21:49 作者:桃花初绽

我是比较新的C#,所以请多多包涵。

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

我想了解任务FromAsync是如何工作的。

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.

推荐答案

FromAsync 提供它采用了方便的机制,在的BeginXXX EndXxx 中的异步编程模型(APM)创建一个工作

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

生成的工作将默认情况下,在一个线程池线程(和你的后续调用若干code1被执行() 的确会在当前线程上执行,在平行于工作)。

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).

工作 ContinueWith 方法确实起到更像一个回调,即提供给此方法的代表将后任务完成,也对的部分的线程池的线程中执行。它的没有的阻止当前线程。

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,...);

有关线程在.NET我全力推荐阅读好文如的通过C# CLR。​​

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#.