Created
June 14, 2014 21:14
-
-
Save Fhernd/6a236e55a3ac471a6c41 to your computer and use it in GitHub Desktop.
Demostración de la técnica de determinación de completitud asincrónica en C#.
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
using System; | |
using System.Threading; | |
namespace Recetas.Cap04 | |
{ | |
public sealed class Blocking | |
{ | |
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 InvocacionAsincronica() | |
{ | |
// Creación de la instancia del delegado, y la | |
// encapsulación del método `ProcesoLargo`: | |
Delegado del = new Delegado (this.ProcesoLargo); | |
// Captura la cadena de caracteres devuelta por llamada | |
// asincrónica al método `ProcesoLargo`: | |
string cadena; | |
// ID del thread que actúo sobre la llamada asincrónica: | |
int threadEjecucion; | |
// Iniciación de la invocación asincrónica del método `ProcesoLargo`: | |
IAsyncResult iar = del.BeginInvoke (3000, out threadEjecucion, null, null); | |
// Aquí se puede escribir código que se ejecutará en paralelo | |
// con la llamada asincrónica al método `ProcesoLargo`: | |
Console.WriteLine ("Esta sentencia se ejecutó mientras el método `ProcesoLargo` está en ejecución."); | |
// Obtiene los resultados de la llamada asincrínica, | |
// Bloque la ejecución del thread principal: | |
cadena = del.EndInvoke (out threadEjecucion, iar); | |
Console.WriteLine(String.Format ("Valor de retorno del delegado \"{0}\" sobre el thread {1}", cadena, threadEjecucion.ToString())); | |
} | |
public static void Main() | |
{ | |
Blocking esm = new Blocking(); | |
esm.InvocacionAsincronica(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment