// OrtizOL - xCSw - http://o...content-available-to-author-only...t.com using System; using System.Threading; using System.Threading.Tasks; namespace Receta.Multithreading.R0208 { public class UsoSpinWait { public static void Main() { Console.WriteLine(Environment.NewLine); bool valorCentinela = false; int numeroCedes = 0; // Contamos con SpinWait mientras que la variable // lógica centinela se hace igual a verdadero: Task t1 = Task.Factory.StartNew(() => { SpinWait sw = new SpinWait(); while (!valorCentinela) { // Determina si se cedió el control al procesador en lugar de // de simple ~girar (spin): if (sw.NextSpinWillYield) { ++numeroCedes; } sw.SpinOnce(); } Console.WriteLine("Número de llamadas de SpinWait: {0} - Cedido {1} veces.", sw.Count, numeroCedes); } ); // En otro thread cambiamos el valor de la variable centinela: Task t2 = Task.Factory.StartNew(() => { Thread.Sleep (200); valorCentinela = true; } ); // Espera hasta que todos los threads finalicen: Task.WaitAll(t1, t2); Console.WriteLine(Environment.NewLine); } } }