// OrtizOL - xCSw - http://ortizol.blogspot.com
using System;
using System.Diagnostics;
using System.Threading;
namespace Receta.CSharp.R0303
{
public class ParalelismoPoolThreads
{
public static void Main()
{
Console.WriteLine(Environment.NewLine);
// Número de operaciones a ejecutar:
const int numeroOperaciones = 500;
// Creación de cronómetro:
Stopwatch sw = new Stopwatch();
// Inicio del cronómetro para medir el tiempo
// que toma la creación de threads:
sw.Start();
UsoThreads(numeroOperaciones);
sw.Stop();
// Obtiene el tiempo transcurrido:
TimeSpan ts = sw.Elapsed;
// Formato de la representación del tiempo
// transcurrido:
string formatoTiempo = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
// Muestro tiempo medido en la creación de de threads:
Console.WriteLine("\nTiempo cronometrizado creación de threads: {0}", formatoTiempo);
Console.WriteLine(Environment.NewLine);
// Reestablece el cronómetro:
sw.Reset();
// Inicia de nuevo la medición. Esta vez para
// el pool de threads:
sw.Start();
UsoPoolThreads(numeroOperaciones);
sw.Stop();
// Obtiene el tiempo transcurrido:
ts = sw.Elapsed;
// Formato de la representación del tiempo
// transcurrido:
formatoTiempo = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
Console.WriteLine("\nTiempo cronometrizado pool de threads: {0}", formatoTiempo);
Console.WriteLine(Environment.NewLine);
}
private static void UsoThreads(int numeroOperaciones)
{
using (CountdownEvent contador = new CountdownEvent(numeroOperaciones))
{
Console.WriteLine ("Inicio de creación de threads para ejecutar operaciones asincrónicas...");
for (int i = 1; i <= numeroOperaciones; ++i)
{
Thread t = new Thread( () => {
Console.Write("{0}, ", Thread.CurrentThread.ManagedThreadId.ToString());
Thread.Sleep(TimeSpan.FromSeconds(0.1));
contador.Signal();
});
t.Start();
}
contador.Wait();
Console.WriteLine();
}
}
private static void UsoPoolThreads(int numeroOperaciones)
{
using (CountdownEvent contador = new CountdownEvent(numeroOperaciones))
{
Console.WriteLine("Inicio de pool de threads...");
for (int i = 1; i <= numeroOperaciones; ++i)
{
ThreadPool.QueueUserWorkItem( _ => {
Console.Write("{0}, ", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(TimeSpan.FromSeconds(0.1));
contador.Signal();
});
}
contador.Wait();
Console.WriteLine ();
}
}
}
}