Home > Blockchain >  Do threads run faster than tasks?
Do threads run faster than tasks?

Time:12-01

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

CodePudding user response:

This line:

Task.Factory.StartNew(LongRunning);

Schedules LongRunning to be run on a thread pool thread. Thread pool is a set of reusable threads, and it has logic behind managing this set of threads. When you attempt to schedule some work to the pool and it does not have a free thread available - it does not necessary spawn a new thread right away. It might wait a bit to see if some of currently busy threads will become available soon.

For this reason it's not a good idea to block thread pool threads for a long time, but this is exactly what you are doing in this example - you block thread pool threads for 3 seconds with Thread.Sleep(3000). First few iterations of your loop take all available thread pool threads, and then on each next iteration thread pool waits a bit to see if one of the existing threads will become available. It does not so then it adds a new thread into the pool and runs your work on it.

This waiting by thread pool is why your "task" code takes more time to complete.

If you intend to perform long blocking operation, you can use:

Task.Factory.StartNew(LongRunning, TaskCreationOptions.LongRunning);
  • Related