I'm trying to learn async/await and created the following test code, however it is running synchronously and I'm not sure why.
class Program
{
static void Main()
{
TestAsync testAsync = new TestAsync();
testAsync.Run();
Console.Read();
}
}
public class TestAsync
{
public async void Run()
{
Task<int> resultTask = GetInt();
Console.WriteLine("2)");
int x = await resultTask;
Console.WriteLine("4)");
}
public async Task<int> GetInt()
{
Task<int> GetIntAfterLongWaitTask = GetIntAfterLongWait();
Console.WriteLine("1)");
int x = await GetIntAfterLongWaitTask;//Expecting execution to go back to Run() since it's not done yet.
Console.WriteLine("3)");
return x;
}
public async Task<int> GetIntAfterLongWait()
{
for (int i = 0; i < 500000000; i++)
{
if (i % 10000000 == 0)
{
Console.WriteLine(i);
}
}
return 23;
}
}
Output is:
<long list of ints>
1)
3)
2)
4)
I expected it to be
<long list of ints>
1)
2)
3)
4)
With 1)
being somewhere amongst the long list of ints.
Why is it running synchronously?
See Question&Answers more detail:os