Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created July 22, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fhernd/736b06027dba15d00e94 to your computer and use it in GitHub Desktop.
Save Fhernd/736b06027dba15d00e94 to your computer and use it in GitHub Desktop.
Paralelismo pool de threads.
// 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 ();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment