Made a time execution comparison between a usual syncronous, asynchronous and a threaded method call with delegates.
//Declare delegate
public delegate void DelGetList(List<int> lista, string tName);
//Create delegate handler
DelGetList delReporter = ReportList;
//Init method
private void Init()
{
TestThreads();
//TestAsynchronous();
//TestSynchronous();
}
private void TestThreads()
{
//Timestamp (will be read at invoked method)
dtStart = DateTime.Now;
//Call main method
Thread t1 = new Thread(new ThreadStart(GetIntsInNewThread));
Thread t2 = new Thread(new ThreadStart(GetIntsInNewThread));
Thread t3 = new Thread(new ThreadStart(GetIntsInNewThread));
var threads = new List<Thread>() { t1, t2, t3 };
foreach (var t in threads)
t.Start();
}
private async void TestAsynchronous()
{
//Timestamp
dtStart = DateTime.Now;
//Call main method
var tasks = new List<Task<List<int>>>();
tasks.Add(TestAsync());
tasks.Add(TestAsync());
tasks.Add(TestAsync());
var test = await Task.WhenAll(tasks);
//Print
System.Console.WriteLine(“Asynchronous, elapsed MS: ” + (DateTime.Now – dtStart).Milliseconds);
}
private void TestSynchronous()
{
//Timestamp
dtStart = DateTime.Now;
//Call main method
var a1 = GetIntsSync();
var a2 = GetIntsSync();
var a3 = GetIntsSync();
//Print
System.Console.WriteLine(“Synchronous, elapsed MS: ” + (DateTime.Now – dtStart).Milliseconds);
}
private List<int> GetIntsSync()
{
List<int> ret = new List<int>();
for (int i = 0; i < 10000000; i++)
{
if (i % 2 == 0 && i / 3 == 1)
ret.Add(i);
}
return ret;
}
private void GetIntsInNewThread()
{
List<int> ret = new List<int>();
for (int i = 0; i < 10000000; i++)
{
if (i % 2 == 0 && i / 3 == 1)
ret.Add(i);
}
delReporter.Invoke(ret, Thread.CurrentThread.Name);
}
private Task<List<int>> TestAsync()
{
return Task.Run(() =>
{
List<int> ret = new List<int>();
for (int i = 0; i < 10000000; i++)
{
if (i % 2 == 0 && i / 3 == 1)
ret.Add(i);
}
return ret;
});
}
//Execution time (3 tests)
Syncronous, elapsed MS: 225
Syncronous, elapsed MS: 223
Syncronous, elapsed MS: 223
Syncronous, elapsed MS: 231
Syncronous, elapsed MS: 231
Asyncronous, elapsed MS: 135
Asyncronous, elapsed MS: 154
Asyncronous, elapsed MS: 149
Asyncronous, elapsed MS: 134
Asyncronous, elapsed MS: 131
Threads, elapsed MS: 134
Threads, elapsed MS: 167
Threads, elapsed MS: 134
Threads, elapsed MS: 147
Threads, elapsed MS: 164