Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement