Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created July 21, 2015 21:17
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/88182ade64a06edabddf to your computer and use it in GitHub Desktop.
Save Fhernd/88182ade64a06edabddf to your computer and use it in GitHub Desktop.
Ejecución operación asincrónica en pool de threads.
// OrtizOL - xCSw - http://ortizol.blogspot.com
using System;
using System.Threading;
namespace Receta.Multithreading.R0302
{
public class OperacionAsincronicaEnPoolThreads
{
public static void Main()
{
Console.WriteLine(Environment.NewLine);
// Variables auxiliares:
const int x = 11;
const int y = 3;
const string estado = "Estado 3 (closure)";
// Pasa implícitamente un objeto WaitCallback:
ThreadPool.QueueUserWorkItem(OperacionAsincronica);
// Esperada simulada en `Main`:
Thread.Sleep(TimeSpan.FromSeconds(1));
// Uso de segunda versión sobrecargada de QueueUserWorkItem:
ThreadPool.QueueUserWorkItem(OperacionAsincronica, "Estado 1 (estándar)");
// Esperada simulada en `Main`:
Thread.Sleep(TimeSpan.FromSeconds(1));
// Uso de versión lambda para operación asincrónica:
ThreadPool.QueueUserWorkItem( obj => {
Console.WriteLine ("Estado operación: {0}", obj);
Console.WriteLine ("ID thread de pool: {0}", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(TimeSpan.FromSeconds(2));
}, "Estado 2 (lambda)" );
// Versión closure:
ThreadPool.QueueUserWorkItem( _ => {
Console.WriteLine ("Estado operación: {0}, {1}", x + y, estado);
Console.WriteLine ("ID thread de pool: {0}", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(TimeSpan.FromSeconds(2));
});
// Esperada simulada en `Main`:
Thread.Sleep(TimeSpan.FromSeconds(2));
Console.WriteLine(Environment.NewLine);
}
// Método de ejecución asincrónica:
private static void OperacionAsincronica(Object estado)
{
Console.WriteLine ("Estado operación: {0}", estado ?? "(null)");
Console.WriteLine ("ID thread de pool: {0}", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(TimeSpan.FromSeconds(2));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment