Created
June 24, 2016 13:37
-
-
Save gandarez/7c8abb16e546213214580e5ec1626179 to your computer and use it in GitHub Desktop.
Callback from Async Task
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.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