// OrtizOL - xCSw - http://o...content-available-to-author-only...t.com using System; using System.Threading; namespace Receta.Multithreading.R0301 { public class InvocacionDelegadoEnPoolThreads { // Declaración de delegado: private delegate string EjecutarEnPoolThread(out int idThread); public static void Main() { Console.WriteLine(Environment.NewLine); int idThread = 0; // Creación de thread (forma tradicional): Thread t = new Thread(() => Proceso(out idThread)); t.Start(); t.Join(); Console.WriteLine("ID Thread: {0}\n", idThread); // Invocación de delegado (método basado en pool de threads): EjecutarEnPoolThread delegadoEnPool = Proceso; IAsyncResult r = delegadoEnPool.BeginInvoke(out idThread, Callback, "Invocación asincrónica de delegado"); r.AsyncWaitHandle.WaitOne(); // Obtiene el resultado de la ejecución de `Proceso`: string resultado = delegadoEnPool.EndInvoke(out idThread, r); Console.WriteLine("ID de thread del pool de threads: {0}", idThread.ToString()); Console.WriteLine(resultado); Thread.Sleep(TimeSpan.FromSeconds(2)); Console.WriteLine(Environment.NewLine); } private static void Callback(IAsyncResult ar) { Console.WriteLine("Inicio de callback..."); Console.WriteLine("Estado de callback: {0}", ar.AsyncState); Console.WriteLine("¿Thread en pool de threads?: {0}", Thread.CurrentThread.IsThreadPoolThread); Console.WriteLine("ID de thread del pool de threads: {0}", Thread.CurrentThread.ManagedThreadId); } private static String Proceso(out int idThread) { Console.WriteLine("Iniciando ejecución de `Proceso`..."); Console.WriteLine("¿Thread en pool de threads?: {0}", Thread.CurrentThread.IsThreadPoolThread); Thread.Sleep(TimeSpan.FromSeconds(2)); idThread = Thread.CurrentThread.ManagedThreadId; return String.Format("ID de thread asignado desde pool de threads: {0}", idThread); } } }