Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. // OrtizOL - xCSw - http://ortizol.blogspot.com
  2.  
  3. using System;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6.  
  7. namespace Receta.Multithreading.R0208
  8. {
  9.     public class UsoSpinWait
  10.     {
  11.         public static void Main()
  12.         {
  13.             Console.WriteLine(Environment.NewLine);
  14.            
  15.             bool valorCentinela = false;
  16.             int numeroCedes = 0;
  17.            
  18.             // Contamos con SpinWait mientras que la variable
  19.             // lógica centinela se hace igual a verdadero:
  20.             Task t1 = Task.Factory.StartNew(() =>
  21.             {
  22.                 SpinWait sw = new SpinWait();
  23.                
  24.                 while (!valorCentinela)
  25.                 {
  26.                     // Determina si se cedió el control al procesador en lugar de
  27.                     // de simple ~girar (spin):
  28.                     if (sw.NextSpinWillYield)
  29.                     {
  30.                         ++numeroCedes;
  31.                     }
  32.                    
  33.                     sw.SpinOnce();
  34.                 }
  35.                
  36.                 Console.WriteLine("Número de llamadas de SpinWait: {0} - Cedido {1} veces.", sw.Count, numeroCedes);
  37.             }
  38.             );
  39.            
  40.             // En otro thread cambiamos el valor de la variable centinela:
  41.             Task t2 = Task.Factory.StartNew(() =>
  42.             {
  43.                 Thread.Sleep (200);
  44.                 valorCentinela = true;
  45.             }
  46.             );
  47.            
  48.             // Espera hasta que todos los threads finalicen:
  49.             Task.WaitAll(t1, t2);
  50.            
  51.             Console.WriteLine(Environment.NewLine);
  52.         }
  53.     }
  54. }