Last active
August 29, 2015 14:25
-
-
Save Fhernd/b2cb6ac260c380579392 to your computer and use it in GitHub Desktop.
Invocación de un delegado en un pool de threads.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// OrtizOL - xCSw - http://ortizol.blogspot.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"); | |
// 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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment