Advertisement
Fhernd

UsoExchange.cs

Aug 7th, 2014
1,575
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.15 KB | None | 0 0
  1. using System;
  2. using System.Threading;
  3.  
  4. namespace Recetas.CSharp.Cap04.R0411
  5. {
  6.     public sealed class UsoExchange
  7.     {
  8.         // Valor de dato compartido entre threads:
  9.         private static int variable = 0;
  10.        
  11.         public static void Main()
  12.         {
  13.             // Creación de un thread:
  14.             Thread t = new Thread(Asignar);
  15.            
  16.             // Inicio de la ejecución del thread:
  17.             t.Start();
  18.            
  19.             // Espera su finalización:
  20.             t.Join();
  21.            
  22.             // Muestra el valor final de `variable`:
  23.             Console.WriteLine ("\nValor de `variable`: {0}\n", variable.ToString());
  24.         }
  25.        
  26.         private static void Asignar()
  27.         {
  28.             // Asigna 10 a `variable`:
  29.             Interlocked.Exchange(ref variable, 10);
  30.            
  31.             // Uso de `Interlocked.CompareExchange`:
  32.             Int32 resultado = Interlocked.CompareExchange(ref variable, 20, 10);
  33.            
  34.             // Muestra en pantalla el valor asignado:
  35.             Console.WriteLine ("\nEl valor de `resultado`: {0}", resultado.ToString());
  36.         }
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement