Skip to content

Instantly share code, notes, and snippets.

@gandarez
Created June 24, 2016 13:37
Show Gist options
  • Save gandarez/7c8abb16e546213214580e5ec1626179 to your computer and use it in GitHub Desktop.
Save gandarez/7c8abb16e546213214580e5ec1626179 to your computer and use it in GitHub Desktop.
Callback from Async Task
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace TaskWithCallback
{
class Program
{
private static readonly object Obj = new object();
static void Main(string[] args)
{
var tasks = new List<Task>
{
Task.Factory.StartNew(() => Run(Callback)),
Task.Factory.StartNew(() => Run(Callback))
};
Task.WaitAll(tasks.ToArray());
}
private static void Run(Action<Result> callback)
{
var result = new Result();
result.DtInicio = DateTime.Now;
result.Total = new Random().Next();
Thread.Sleep(new Random().Next(100, 3000));
result.DtFinal = DateTime.Now;
callback(result);
}
private static void Callback(Result result)
{
lock (Obj)
{
Console.WriteLine(result.DtInicio.ToString("dd/MM/yyyy HH:mm:sss"));
Console.WriteLine(result.Total);
Console.WriteLine(result.DtFinal.ToString("dd/MM/yyyy HH:mm:sss"));
}
}
}
class Result
{
public DateTime DtInicio { get; set; }
public DateTime DtFinal { get; set; }
public int Total { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment