I'm new to C# and for now I'm trying to understand async/await feautures. So I have created small sandbox app:
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();
}
}
}
But the result is weird:
Async
OneTwoThree
1754
Sync
OneTwoThree
1506
Async method runs longer than similar sync one. For me it's look like async methods runs synchronously but I cant figure out why.
async/awaitor (b) can't explain themawaitoperator does? I am interested to know how people's intuitions about programming language constructs lead them astray. An await is an asynchronous wait; the intention was to give you the intuition that you will be waiting for the result of the task, but still doing other work on the current thread while you're waiting. In what ways did we fail to give you the correct intuition, and how could it be better?