我想了解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/。從底部開始,這些列表從大多數到最近都列出。 –