我想了解TPL。不幸的是,我无法用返回类型来克服任务。从我读过的内容来看,我认为将任务分配给变量会异步启动。当您需要返回值时,您只需等待它,这可确保当前线程等待Task<T>
完成。在MSDN为什么任务<TResult>在等待结果前等待结果?
例子:
// 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的一系列文章是对这个主题的一个很好的介绍。 http://blog.stephencleary.com/2012/02/async-and-await.html –
是的,很遗憾,我错误地了解了我所学到的大部分内容。 – Sorashi
这是棘手的东西。如果你想要更多的技术性的东西,虽然这个东西有点过时,但是当我们设计它的时候,我写了一系列文章。 https://blogs.msdn.microsoft.com/ericlippert/tag/async/。从底部开始,这些列表从大多数到最近都列出。 –