using System; using System.Threading; namespace Recetas.Multithreading.Cap01.R0108 { // Clase utilitaria como contenedora de datos // para un método método ejecutado en un thread: public class UtilitarioThread { private readonly int _iteraciones; public UtilitarioThread (int iteraciones) { _iteraciones = iteraciones; } // Imprime los números desde el 1 hasta // el número de iteraciones: public void ContarNumeros() { for (int i = 1; i <= _iteraciones; ++i) { Thread.Sleep (TimeSpan.FromSeconds(0.5)); Console.WriteLine ("El thread `{0}` imprime {1}", Thread.CurrentThread.Name, i.ToString() ); } } } public sealed class ParametrosThread { // Método static para contar números según // el argumento pasado al inicio de la // ejecución de un thread: private static void Contar (object iteraciones) { ContarNumeros((int)iteraciones); } // Imprime los números desde el 1 hasta // el número de iteraciones: private static void ContarNumeros(int iteraciones) { for (int i = 1; i <= iteraciones; ++i) { Thread.Sleep (TimeSpan.FromSeconds(0.5)); Console.WriteLine ("El thread `{0}` imprime {1}", Thread.CurrentThread.Name, i.ToString() ); } } // Imprime un número en la salida estándar: private static void ImprimirNumero(int numero) { Console.WriteLine (numero.ToString()); } public static void Main() { Console.Title = "Pasar Parámetros a un Thread"; Console.WriteLine (); // Creación de instancia de la clase UtilitarioThread: UtilitarioThread ut = new UtilitarioThread(10); Console.WriteLine ("=== Uso de Thread.Start() ==="); Thread t1 = new Thread (ut.ContarNumeros); t1.Name = "Thread No. 1"; t1.Start(); t1.Join (); Console.WriteLine ("\n=== Uso de Thread.Start(Object) ==="); Thread t2 = new Thread (new ParameterizedThreadStart(Contar)); t2.Name = "Thread No. 2"; t2.Start (8); t2.Join(); Console.WriteLine ("\n=== Uso de Expresión Lambda (1)==="); Thread t3 = new Thread (() => ContarNumeros(12)); t3.Name = "Thread No. 3"; t3.Start(); t3.Join(); Console.WriteLine ("\n=== Uso de Expresión Lambda (2)==="); int numero = 11; Thread t4 = new Thread(() => ImprimirNumero(numero)); numero = 13; Thread t5 = new Thread(() => ImprimirNumero(numero)); t4.Start(); t5.Start(); } } }