Do threads run faster than tasks?
The speed of my application improved only by replacing one line of code with thread that used task.
As a result, I decided to conduct a small experiment as follows:
using System.Diagnostics;
void LongRunning()
{
Thread.Sleep(3000);
}
Stopwatch s1 = new Stopwatch();
TimeSpan ts;
string elapsedTime;
//thread----------------------
s1.Reset();
s1.Start();
var threadList = new List<Thread>();
for (int i = 0; i < 100; i++)
{
Thread t = new Thread(LongRunning);
threadList.Add(t);
t.Start();
}
foreach (var th in threadList)
{
th.Join();
}
s1.Stop();
ts = s1.Elapsed;
elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime Thread " + elapsedTime);
//task----------------------
s1.Reset();
s1.Start();
var taskList = new List<Task>();
for (int i = 0; i < 100; i++)
taskList.Add(Task.Factory.StartNew(LongRunning));
Task.WaitAll(taskList.ToArray());
s1.Stop();
ts = s1.Elapsed;
elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime Task " + elapsedTime);
Console.ReadLine();
By using tasks, it takes ~25 seconds, and by using thread, it takes only ~4 seconds