Created
June 23, 2016 21:39
-
-
Save Fhernd/a46380e188d85a3098e10755f273efa6 to your computer and use it in GitHub Desktop.
Ejecución en paralelo de múltiples tareas. [OrtizOL]
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 Recetas.Multithreading.R0408 | |
{ | |
public class EjecuionMultiplesTareas | |
{ | |
public static void Main() | |
{ | |
Console.WriteLine (); | |
Task<int> tarea1 = new Task<int>( () => Tarea("Tarea No. 1", 3)); | |
Task<int> tarea2 = new Task<int>( () => Tarea("Tarea No. 2", 2)); | |
var tareaCompuesta = Task.WhenAll(tarea1, tarea2); | |
// Continuación para la tarea compuesta: | |
tareaCompuesta.ContinueWith( t => | |
Console.WriteLine ("Primera respuesta {0}, segunda respuesta: {1}.", | |
t.Result[0], t.Result[1])); | |
// Inicio ejecución tareas: | |
tarea1.Start(); | |
tarea2.Start(); | |
// Suspensión temporal: | |
Thread.Sleep(TimeSpan.FromSeconds(4)); | |
Console.WriteLine (); | |
// Conjunto de tareas: | |
var tareas = new List<Task<int>>(); | |
// Creación conjunto de tareas: | |
for (int i = 3; i < 6; ++i) | |
{ | |
int contador = i; | |
Task<int> tarea = new Task<int>( () => Tarea( | |
String.Format("Tarea No. {0}", contador), contador)); | |
tareas.Add(tarea); | |
tarea.Start(); | |
} | |
// Mientras que hayan tareas por terminar: | |
while (tareas.Count > 0) | |
{ | |
// Obtiene cualquiera de las tareas que haya terminado: | |
var tareaCompletada = Task.WhenAny(tareas).Result; | |
// Elimina la tarea que ya terminó de la lista: | |
tareas.Remove(tareaCompletada); | |
// Muestra en la salida estándar el resultado de la tarea terminada: | |
Console.WriteLine ("La tarea que acaba de terminar generó como resultado: {0}.", | |
tareaCompletada.Result); | |
} | |
Console.WriteLine (); | |
} | |
public static int Tarea(string nombre, int duracion) | |
{ | |
Console.WriteLine("La tarea `{0}` se está ejecutando en el ID de Thread {1}. " | |
+ "¿Thread en pool de threads?: {2}", nombre, | |
Thread.CurrentThread.ManagedThreadId, | |
Thread.CurrentThread.IsThreadPoolThread); | |
// Simulación de ejecución tardía: | |
Thread.Sleep (TimeSpan.FromSeconds(duracion)); | |
return 42 * duracion; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment