Reputation: 4593
static void Main(string[] args)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Task t = MainAsync();
t.Wait();
stopWatch.Stop();
var sec = stopWatch.ElapsedMilliseconds;
}
static async Task MainAsync()
{
FutureEntityTestEntities db = new FutureEntityTestEntities();
var q1 = await db.Table1.ToListAsync();
var q2 = await db.Table1.ToListAsync();
}
this query takes 2700 miliseconds on average.
however when i just do normal tolist without async it takes 1800 ms;
static void Main(string[] args)
{
FutureEntityTestEntities db = new FutureEntityTestEntities();
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
var q1 = db.Table1.ToList();
var q2 = db.Table1.ToList();
stopWatch.Stop();
Console.WriteLine(stopWatch.ElapsedMilliseconds);
Console.ReadLine();
}
the problem is i dont understand, it should take what the synchronous time divided by 2 = 900ms but it adds another 900 ms which is fairly strange.
Edit: Thx for the answer now.I modified the code as follows:
static void Main(string[] args)
{
Stopwatch stopWatch2;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Task t = MainAsync();
stopWatch.Stop();
Console.WriteLine(stopWatch.ElapsedMilliseconds);
Console.ReadLine();
}
static async Task MainAsync()
{
FutureEntityTestEntities db = new FutureEntityTestEntities();
Task<List<Table1>> q1 = db.Table1.ToListAsync();
Task<List<Table1>> q2 = db.Table1.ToListAsync();
await Task.WhenAll(q1, q2);
}
now however it takes on average 500 ms.
I am going to research on the internet as to why and post the answer here, if somebody has an answer please respond thx.
Upvotes: 1
Views: 121
Reputation: 149538
the problem is i dont understand, it should take what the synchronous time divided by 2
That's incorrect. These two queries aren't running concurrently, they're running sequentiality one after the other. await
means: asynchronously wait for the operation to complete.
If you want to execute them concurrently, you can spin of both operations and then use await Task.WhenAll
and pass in both tasks.
As a side note, using async-await
doesn't come for free. There's the compiler which does work for us of generating a state-machine behind the scenes. Although very optimized, still has some overhead.
Upvotes: 4
Reputation: 33379
You're not concurrently executing the two .ToListAsync()
's if that's what you're expecting. If you wanted them to execute concurrently you would need to do:
// Kick off both queries concurrency
Task<List<Table1>> q1 = db.Table1.ToListAsync();
Task<List<Table1>> q2 = db.Table1.ToListAsync();
// Wait for both to finish before returning
await Task.WhenAll(q1, q2);
Upvotes: 4