using System;
using System.Threading;
namespace Recetas.CSharp.Cap04.R0411
{
public sealed class UsoExchange
{
// Valor de dato compartido entre threads:
private static int variable = 0;
public static void Main()
{
// Creación de un thread:
Thread t = new Thread(Asignar);
// Inicio de la ejecución del thread:
t.Start();
// Espera su finalización:
t.Join();
// Muestra el valor final de `variable`:
Console.WriteLine ("\nValor de `variable`: {0}\n", variable.ToString());
}
private static void Asignar()
{
// Asigna 10 a `variable`:
Interlocked.Exchange(ref variable, 10);
// Uso de `Interlocked.CompareExchange`:
Int32 resultado = Interlocked.CompareExchange(ref variable, 20, 10);
// Muestra en pantalla el valor asignado:
Console.WriteLine ("\nEl valor de `resultado`: {0}", resultado.ToString());
}
}
}
dXNpbmcgU3lzdGVtOwp1c2luZyBTeXN0ZW0uVGhyZWFkaW5nOwoKbmFtZXNwYWNlIFJlY2V0YXMuQ1NoYXJwLkNhcDA0LlIwNDExCnsKICAgIHB1YmxpYyBzZWFsZWQgY2xhc3MgVXNvRXhjaGFuZ2UKICAgIHsKICAgICAgICAvLyBWYWxvciBkZSBkYXRvIGNvbXBhcnRpZG8gZW50cmUgdGhyZWFkczoKICAgICAgICBwcml2YXRlIHN0YXRpYyBpbnQgdmFyaWFibGUgPSAwOwogICAgICAgIAogICAgICAgIHB1YmxpYyBzdGF0aWMgdm9pZCBNYWluKCkKICAgICAgICB7CiAgICAgICAgICAgIC8vIENyZWFjacOzbiBkZSB1biB0aHJlYWQ6CiAgICAgICAgICAgIFRocmVhZCB0ID0gbmV3IFRocmVhZChBc2lnbmFyKTsKICAgICAgICAgICAgCiAgICAgICAgICAgIC8vIEluaWNpbyBkZSBsYSBlamVjdWNpw7NuIGRlbCB0aHJlYWQ6CiAgICAgICAgICAgIHQuU3RhcnQoKTsKICAgICAgICAgICAgCiAgICAgICAgICAgIC8vIEVzcGVyYSBzdSBmaW5hbGl6YWNpw7NuOgogICAgICAgICAgICB0LkpvaW4oKTsKICAgICAgICAgICAgCiAgICAgICAgICAgIC8vIE11ZXN0cm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