Created
March 25, 2016 20:26
-
-
Save Fhernd/16399bed6597151e8a04 to your computer and use it in GitHub Desktop.
Invocación sincrónica y asincrónica.
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; | |
using System.Threading.Tasks; | |
namespace Recetas.Multithreading.R0402 | |
{ | |
public class PoolThreadsVsMainThread | |
{ | |
public static void Main() | |
{ | |
Console.WriteLine ("\nAplicación consola ejecutándose sobre el ID thread: {0}", | |
Thread.CurrentThread.ManagedThreadId); | |
var taskAsincronico = Task.Run ( () => | |
{ | |
Console.WriteLine ("ID Task {0} (asincrónico) ejecutándose sobre el ID de Thread: {1}", | |
Task.CurrentId, | |
Thread.CurrentThread.ManagedThreadId); | |
long suma = 0; | |
// Cálculo de la suma entre 1 y 1000000: | |
for ( int i = 1; i <= 1000000; ++i) | |
{ | |
suma += i; | |
} | |
return suma; | |
} | |
); | |
var taskSincronico = new Task<long> ( () => | |
{ | |
Console.WriteLine ("ID Task {0} (sincrónico) ejecutándose sobre el ID de Thread: {1}", | |
Task.CurrentId, | |
Thread.CurrentThread.ManagedThreadId); | |
long suma = 0; | |
// Cálculo de la suma entre 1 y 1000000: | |
for ( int i = 1; i <= 1000000; ++i) | |
{ | |
suma += i; | |
} | |
return suma; | |
} | |
); | |
// Inicio de ejecución Task sincrónico: | |
taskSincronico.RunSynchronously(); | |
Console.WriteLine (); | |
// Visualización de resultados: | |
Console.WriteLine ("ID Task {0} retornó: {1:N0}", taskSincronico.Id, taskSincronico.Result); | |
Console.WriteLine ("ID Task {0} retornó: {1:N0}\n", taskAsincronico.Id, taskAsincronico.Result); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment