I was playing with Async and made a sample program below. The sample program compares time spent for synchronous and asynchronous operations
I was expecting that async operations will take lesser time, considering that tasks run in parallel on background thread. But the program below takes equal time for both sync and async operations. I think I am missing something, but everywhere I get the following example to create async task and run them
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AsyncTest {
class Program {
private static long max = 100;
static void Main(string[] args) {
var startTime = DateTime.Now;
Console.WriteLine("Start Process at");
//Normal(); //takes about 20 secs
MainAsync().Wait(); //takes about 20 secs
Console.WriteLine($"Total Time Taken {DateTime.Now.Subtract(startTime).TotalMilliseconds} ms");
Console.ReadKey();
}
static void Normal() {
for (long i = 0; i <= max; ++i) {
Thread.Sleep(200);
}
}
static async Task MainAsync() {
var runner = new Runner();
for (int i = 0; i <= 100; ++i) {
await runner.Run(i, max / 100);
}
}
}
public class Runner {
public async Task Run(int idx, long max) {
await Task.Run(() => {
for (long i = 1; i <= max; ++i) {
Console.WriteLine($"Task {idx} - {i}");
Thread.Sleep(200);
}
});
}
}
}
Any help what am I missing here ?