我是C#的新手,現在我想了解異步/等待特徵。所以,我創建了小沙盒應用程序:C#異步等待怪異行爲
namespace sandbox
{
public class Test
{
public async Task<string> GetItemsAsync()
{
var a = await Task1();
var b = await Task2();
var c = await Task3();
return a + b + c;
}
public string GetItems()
{
return _T1() + _T2() + _T3();
}
private readonly int cycles = 100000000;
private async Task<string> Task1()
{
return await Task.Factory.StartNew(_T1);
}
private async Task<string> Task2()
{
return await Task.Factory.StartNew(_T2);
}
private async Task<string> Task3()
{
return await Task.Factory.StartNew(_T3);
}
// long running operation
private string _T1()
{
for (int i = 0; i < cycles; i++) ;
for (int i = 0; i < cycles; i++) ;
return "One";
}
// long running operation
private string _T2()
{
for (int i = 0; i < cycles; i++) ;
for (int i = 0; i < cycles; i++) ;
return "Two";
}
// long running operation
private string _T3()
{
for (int i = 0; i < cycles; i++) ;
for (int i = 0; i < cycles; i++) ;
return "Three";
}
}
class Program
{
static void Main(string[] args)
{
var t = new Test();
Console.WriteLine("Async");
Stopwatch sw = new Stopwatch();
sw.Start();
var result = t.GetItemsAsync();
Console.WriteLine(result.Result);
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
Console.WriteLine("Sync");
sw.Restart();
var strResult = t.GetItems();
Console.WriteLine(strResult);
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
Console.ReadLine();
}
}
}
但結果是怪異:
Async
OneTwoThree
1754
Sync
OneTwoThree
1506
異步方法運行時間比類似的同步之一。對我來說,它看起來像異步方法同步運行,但我不知道爲什麼。
因爲你等待所有人同步。 – Liam
通過等待任務的您正在將其從異步更改爲同步,await關鍵字將暫停當前任務並且不會繼續,直到等待完成的任務完成 – MikeT
使用await將使代碼同步運行並且還會增加開銷創建一個狀態機(每次使用'await'),所以它的運行速度也比同步運行慢。 – Igor