Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Last active August 29, 2015 14:25
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/b2cb6ac260c380579392 to your computer and use it in GitHub Desktop.
Save Fhernd/b2cb6ac260c380579392 to your computer and use it in GitHub Desktop.
Invocación de un delegado en un pool de threads.
// 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