我是 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();
谢谢你的帮助,我真的在为异步编程而苦苦挣扎。
最佳答案
FromAsync
提供了一种方便的机制,它使用 Asynchronous Programming Model (APM) 的 BeginXxx
和 EndXxx
方法创建一个任务
。
默认情况下,生成的 Task
将在线程池线程上执行(并且您对 SomeCode1()
的后续调用确实会在当前线程上执行,在与 Task
并行)。
Task
上的 ContinueWith
方法确实很像回调,即提供给此方法的委托(delegate)将在任务完成后执行,同样在 一些 线程池线程。它不会阻塞当前线程。
确实,您应该在创建任务时设置此延续,例如
var task1 = Task<int>.Factory.FromAsync(Foo1, ...).ContinueWith(Foo2,...);
有关 .NET 中线程的更多一般和详细信息,我强烈建议您阅读不错的文本,例如 CLR via C# 的第 V 部分| .
关于c# - Task.Factory.FromAsync 如何工作/表现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7784589/