Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. using System;
  2. using System.Threading;
  3.  
  4. namespace Recetas.Cap04
  5. {
  6.     public sealed class Callback
  7.     {
  8.         string ProcesoLargo (int tiempoRetraso, out int threadEjecucion)
  9.         {
  10.             Thread.Sleep (tiempoRetraso);
  11.             threadEjecucion = AppDomain.GetCurrentThreadId();;
  12.             return String.Format ("Tiempo de retraso: {0}", tiempoRetraso.ToString());
  13.         }
  14.        
  15.         delegate string Delegado (int tiempoRetraso, out int threadEjecucion);
  16.        
  17.         public void RespuestaAsyncCallback (IAsyncResult iac)
  18.         {
  19.             string respuesta;
  20.             int idThread;
  21.            
  22.             Delegado del = (Delegado) iac.AsyncState;
  23.            
  24.             // Completitud de la invocación:
  25.             respuesta = del.EndInvoke (out idThread, iac);
  26.            
  27.             Console.WriteLine(String.Format  ("Valor de retorno del delegado \"{0}\" sobre el thread {1}", respuesta, idThread.ToString()));
  28.         }
  29.        
  30.         public void InvocacionAsincronica()
  31.         {
  32.             // Creación de la instancia del delegado, y la
  33.             // encapsulación del método `ProcesoLargo`:
  34.             Delegado del = new Delegado (this.ProcesoLargo);
  35.            
  36.             // ID del thread que actúo sobre la llamada asincrónica:
  37.             int threadEjecucion;
  38.            
  39.             // Crea delegado AsyncCallback:
  40.             AsyncCallback cb = new AsyncCallback (RespuestaAsyncCallback);
  41.            
  42.             // Iniciación de la invocación asincrónica del método `ProcesoLargo`:
  43.             IAsyncResult iar = del.BeginInvoke (3000, out threadEjecucion, RespuestaAsyncCallback, del);
  44.            
  45.             Console.WriteLine ("Esta línea de código se ejecutó inmediatamente despues `BeginInvoke`.");
  46.         }
  47.        
  48.         public static void Main()
  49.         {
  50.             Callback esm = new Callback();
  51.             esm.InvocacionAsincronica();
  52.         }
  53.     }
  54. }