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

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

谢谢你的帮助,我真的在为异步编程而苦苦挣扎。

最佳答案

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

默认情况下,生成的 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/

相关文章:

c# - BTS 2013 - 消息的消息签名错误

.net - 找不到 "Microsoft.NET.CoreRuntime"

c# - Intellisense - 字符串中的 Javascript

c# - 当装箱类型未知时检查不同类型的装箱值类型是否相等

c# - 控制台暂停方式

.net - 在设计时隐藏私有(private)子控件属性

c# - 为什么是 "Using asynchronous [...] methods on CPU-bound [providing] no benefits and results in more overhead."

php - 如何在 PHP/Windows 中异步任务结束时通知用户

javascript - 如何从异步调用返回响应?

c# - 通过代码向hadoop作业提供输入