Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created February 24, 2018 23:30
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/68fb9bbfca7d4248821f25ff37cee5e3 to your computer and use it in GitHub Desktop.
Save Fhernd/68fb9bbfca7d4248821f25ff37cee5e3 to your computer and use it in GitHub Desktop.
Uso de asincronismo con tipos dinámicos en C#.
using System;
using System.Dynamic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using ImpromptuInterface;
namespace R5._9OperadorAwaitConDynamic
{
class Programa
{
/// <summary>
/// Inicia la ejecución de la aplicación.
/// </summary>
static void Main()
{
Task nuevaTarea = ProcesamientoAsincronico();
nuevaTarea.Wait();
}
/// <summary>
/// Inicia el procesamiento asincrónica de una tarea.
/// </summary>
/// <returns>Tarea</returns>
async static Task ProcesamientoAsincronico()
{
string resultado = await ObtenerObjetoAwaitDinamico(true);
Console.WriteLine(resultado);
resultado = await ObtenerObjetoAwaitDinamico(false);
Console.WriteLine(resultado);
}
/// <summary>
/// Obtiene un objeto dinámico a partir de la ejecución sincrónica o asincrónica de una tarea que
/// a de completarse después un segundo.
/// </summary>
/// <param name="completarConSincronismo">Determina si la tarea se ejecuta sincrónica o asincrónicamente.</param>
/// <returns>Objeto dinámico</returns>
static dynamic ObtenerObjetoAwaitDinamico(bool completarConSincronismo)
{
dynamic resultado = new ExpandoObject();
dynamic awaiter = new ExpandoObject();
awaiter.Message = "Proceso completado sincrónicamente";
awaiter.IsCompleted = completarConSincronismo;
awaiter.GetResult = (Func<string>)(() => awaiter.Message);
awaiter.OnCompleted = (Action<Action>)(callback =>
ThreadPool.QueueUserWorkItem(state => {
Thread.Sleep(TimeSpan.FromSeconds(1));
awaiter.Message = ObtenerMensajes();
if (callback != null)
{
callback();
}
})
);
IAwaiter<string> proxy = Impromptu.ActLike(awaiter);
resultado.GetAwaiter = (Func<dynamic>)(() => proxy);
return resultado;
}
/// <summary>
/// Muestra la información actual del thread en ejecución.
/// </summary>
/// <returns>Información actual del thread en ejecución.</returns>
static string ObtenerMensajes()
{
return string.Format("La tarea se está ejecutando en el thread con ID: {0}. ¿Thread en el pool de threads?: {1} ", Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);
}
public interface IAwaiter<T> : INotifyCompletion
{
bool IsCompleted { get; }
T GetResult();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment