Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created June 14, 2014 23:30
Show Gist options
  • Save Fhernd/02fcdf52c0f12776188d to your computer and use it in GitHub Desktop.
Save Fhernd/02fcdf52c0f12776188d to your computer and use it in GitHub Desktop.
Demostración del patrón callback para llamadas asincrónicas de métodos en C#.
using System;
using System.Threading;
namespace Recetas.Cap04
{
public sealed class Callback
{
string ProcesoLargo (int tiempoRetraso, out int threadEjecucion)
{
Thread.Sleep (tiempoRetraso);
threadEjecucion = AppDomain.GetCurrentThreadId();;
return String.Format ("Tiempo de retraso: {0}", tiempoRetraso.ToString());
}
delegate string Delegado (int tiempoRetraso, out int threadEjecucion);
public void RespuestaAsyncCallback (IAsyncResult iac)
{
string respuesta;
int idThread;
Delegado del = (Delegado) iac.AsyncState;
// Completitud de la invocación:
respuesta = del.EndInvoke (out idThread, iac);
Console.WriteLine(String.Format ("Valor de retorno del delegado \"{0}\" sobre el thread {1}", respuesta, idThread.ToString()));
}
public void InvocacionAsincronica()
{
// Creación de la instancia del delegado, y la
// encapsulación del método `ProcesoLargo`:
Delegado del = new Delegado (this.ProcesoLargo);
// ID del thread que actúo sobre la llamada asincrónica:
int threadEjecucion;
// Crea delegado AsyncCallback:
AsyncCallback cb = new AsyncCallback (RespuestaAsyncCallback);
// Iniciación de la invocación asincrónica del método `ProcesoLargo`:
IAsyncResult iar = del.BeginInvoke (3000, out threadEjecucion, RespuestaAsyncCallback, del);
Console.WriteLine ("Esta línea de código se ejecutó inmediatamente despues `BeginInvoke`.");
}
public static void Main()
{
Callback esm = new Callback();
esm.InvocacionAsincronica();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment