I have my Program.cs file:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace AsyncTest
{
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("Hello World!");
var interesting = new InterestingObject();
List<int> list;
List<int> alsoList;
list = await interesting.GenerateListAsync();
alsoList = interesting.GenerateList();
Console.WriteLine("Done! :)");
list .ForEach(xs => Console.WriteLine(xs));
alsoList.ForEach(xs => Console.WriteLine (xs));
}
}
}
And here's the code for InterestingObject:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace AsyncTest
{
public class InterestingObject
{
public InterestingObject()
{
}
public List<int> GenerateList()
{
Console.WriteLine("Gonna generate the list!");
var list = new List<int>();
int i = 0;
while (i < 5)
{
Random random = new Random();
list.Add(random.Next());
Console.WriteLine("Generated a new int!");
VeryHeavyCalculations();
i++;
}
return list;
}
public async Task<List<int>> GenerateListAsync()
{
Console.WriteLine("Gonna generate the list async!");
var list = new List<int>();
int i = 0;
while (i < 5)
{
Random random = new Random();
list.Add(random.Next ());
Console.WriteLine("Generated a new int asyncronously!");
await Task.Run(() => VeryHeavyCalculations());
i++;
}
return list;
}
public void VeryHeavyCalculations()
{
Thread.Sleep (1000);
}
}
}
I expect list = await interesting.GenerateListAsync(); to run asynchronously while alsoList = interesting.GenerateList(); is running, effectively logging the output of GenerateList into my console while GenerateListAsync is doing the exact same, or to see GenerateListAsync finish near-instantly when GenerateList finishes.
However, looking into the console I see my application running GenerateListAsync and then run GenerateList afterwards.
I'm doing this wrong but no source has been sufficient to solve this problem.
await. If you want to kick that operation off and then move on then do notawaitthe Task until some point later in your code.new Random()in a loop. That's not going to end well for you. You're just going to create it with the same seed, and it's going to generate the same numbers.await's ahead, and it will run those asynchronously while it runs all the code preceding it?