【发布时间】:2016-03-06 19:37:53
【问题描述】:
我正在尝试理解 TPL。不幸的是,我无法克服返回类型的任务。根据我的阅读,我认为将任务分配给变量会异步启动它。当你需要返回值时,你就等待它,这样可以保证当前线程等待Task<T>完成。
MSDN 上的示例:
// Call and await in separate statements.
Task<int> integerTask = TaskOfT_MethodAsync();
// You can do other work that does not rely on integerTask before awaiting.
textBox1.Text += String.Format("Application can continue working while the Task<T> runs. . . . \r\n");
int result2 = await integerTask;
我的理解:第一条语句应该开始任务,之后立即附加文本框。然后线程被阻塞直到integerTask完成。
但是,当我自己尝试时,它并没有这样工作:
static void Main()
{
var task = new Task(RunItAsync);
task.Start();
task.Wait();
}
static async void RunItAsync()
{
// Should start the task, but should not block
var task = GetIntAsync();
Console.WriteLine("I'm writing something while the task is running...");
// Should wait for the running task to complete and then output the result
Console.WriteLine(await task);
}
static Random r = new Random();
static async Task<int> GetIntAsync()
{
return await Task.FromResult(GetIntSync());
}
public static int GetIntSync()
{
// Some long operation to hold the task running
var count = 0;
for (var i = 0; i < 1000000000; i++) {
if (i % 2 == 0) count++;
}
return r.Next(count);
}
没有输出,几秒钟后立即输出所有内容:
I'm writing something while the task is running...
143831542
我做错了什么?
【问题讨论】:
-
我认为你需要退后一步,更彻底地理解使异步工作所需的所有概念。 Stephen Cleary 的系列文章很好地介绍了该主题。 blog.stephencleary.com/2012/02/async-and-await.html
-
是的,很遗憾,我学到的大部分东西都错了。
-
这很棘手。如果您想要对这些东西进行更技术性的介绍,尽管有些过时,我在设计它时写了一系列文章。 blogs.msdn.microsoft.com/ericlippert/tag/async。从底部开始,这些是从最近到最近的。
-
感谢您的帮助,我会调查的
标签: c# asynchronous async-await task-parallel-library