Following is the code which we should be writing to fulfill your conditions:
async Task<List<int>> Counting()
{
Console.WriteLine("....something else...Started");
List<int> nums = new List<int>();
for (int i = 0; i < 100; i++)
{
await Task.Delay(100);
nums.Add(i);
}
Console.WriteLine(".....something else...Done");
return nums;
}
public async void AsyncAndAwait()
{
Console.WriteLine("AsyncAndAwait starting...");
Task<List<int>> task = Counting();
Console.WriteLine("Doing something else...");
List<int> list = task.Result;
Console.WriteLine("I am done!!!");
}
public void RunTest()
{
AsyncAndAwait();
}
I can see few reasons why your code is not giving desired behaviors:
1. Just putting async while declaring method does not make it asynchronous method. There must be await inside it. As stated at
MSDN page : "If the method that the async keyword modifies doesn't contain an await expression or statement, the method executes synchronously." That's why instead of "Thread.Sleep(100)" I used "await Task.Delay(100)".
2. Just by writing "var task = Counting()", you are calling "Counting" method on same thread. if you will not use await keyword it is a blocking call. As stated at
MSDN page : "An await expression does not block the thread on which it is executing." For more please visit:
http://stackoverflow.com/questions/23022573/calling-async-methods-from-a-synchronous-context[
^]
Hope it will help. Thanks.