I wrote some function to compare the duration taken for 1000 loops. Just wondering if the comparison is right? For the thread, I want to set to maximum 3 thread. Thread is core
, right? Task
took the longest time which seems not correct.
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Multithreading_Loop
{
class Program
{
static void Main(string[] args)
{
//PrintLoopWithoutThread();
//PrintLoopWithThread();
//PrintLoopWithTaskWaitAll();
//PrintLoopWithParallelFor();
PrintLoopWithParallelForEach();
}
/// <summary>
/// Elapsed time: 4.13 seconds
/// </summary>
private static void PrintLoopWithoutThread()
{
Stopwatch sw = new Stopwatch();
sw.Start();
for (var x = 1; x <= 1000; x++)
{
Console.WriteLine($"Worker Id: {Thread.CurrentThread.ManagedThreadId}");
Console.WriteLine(x);
}
sw.Stop();
Console.WriteLine(sw.Elapsed.TotalSeconds);
}
/// <summary>
/// Elapsed time: 11.4 seconds
/// </summary>
private static void PrintLoopWithThread()
{
Stopwatch sw = new Stopwatch();
sw.Start();
Thread t1 = new Thread(PrintLoopWithoutThread);
t1.Start();
Thread t2 = new Thread(PrintLoopWithoutThread);
t2.Start();
Thread t3 = new Thread(PrintLoopWithoutThread);
t3.Start();
t1.Join();
t2.Join();
t3.Join();
sw.Stop();
Console.WriteLine(sw.Elapsed.TotalSeconds);
}
/// <summary>
/// Elapsed time: 15.5 seconds
/// </summary>
private static void PrintLoopWithTaskWaitAll()
{
Task task1 = Task.Factory.StartNew(() => PrintLoopWithoutThread());
Task task2 = Task.Factory.StartNew(() => PrintLoopWithoutThread());
Task task3 = Task.Factory.StartNew(() => PrintLoopWithoutThread());
Task.WaitAll(task1, task2, task3);
}
/// <summary>
/// Elapsed time: 2.2 seconds
/// </summary>
private static void PrintLoopWithParallelFor()
{
Stopwatch sw = new Stopwatch();
sw.Start();
Parallel.For(0, 999, x =>
{
Console.WriteLine($"WorkerId: {Task.CurrentId}. Number: " + x);
});
sw.Stop();
Console.WriteLine(sw.Elapsed.TotalSeconds);
}
/// <summary>
/// Elapsed time: 2.0 seconds
/// </summary>
private static void PrintLoopWithParallelForEach()
{
Stopwatch sw = new Stopwatch();
sw.Start();
var data = Enumerable.Range(0, 999);
// If computer has 4 cores and you want to use the maximum 4,
// then put MaxDegreeOfParallelism = 4
Parallel.ForEach(data, new ParallelOptions { MaxDegreeOfParallelism = 4 }, i =>
{
Console.WriteLine($"WorkerId: {Task.CurrentId}. Number: " + i);
});
sw.Stop();
Console.WriteLine(sw.Elapsed.TotalSeconds);
}
}
}