本文整理汇总了C#中System.Threading.Interlocked.Exchange方法的典型用法代码示例。如果您正苦于以下问题:C# Interlocked.Exchange方法的具体用法?C# Interlocked.Exchange怎么用?C# Interlocked.Exchange使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Threading.Interlocked
的用法示例。
在下文中一共展示了Interlocked.Exchange方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
//引入命名空间
using System;
using System.Threading;
class MainClass
{
public static void Main()
{
int firstInt = 25;
int secondInt = 80;
Console.WriteLine("firstInt initial value = {0}", firstInt);
Console.WriteLine("secondInt initial value = {0}", secondInt);
Interlocked.Exchange(ref secondInt, firstInt);
Console.WriteLine("firstInt after Exchange = {0}", firstInt);
Console.WriteLine("secondInt after Exchange = {0}", secondInt);
}
}
示例2: Main
//引入命名空间
using System;
using System.Threading;
namespace InterlockedExchange_Example
{
class MyInterlockedExchangeExampleClass
{
//0 for false, 1 for true.
private static int usingResource = 0;
private const int numThreadIterations = 5;
private const int numThreads = 10;
static void Main()
{
Thread myThread;
Random rnd = new Random();
for(int i = 0; i < numThreads; i++)
{
myThread = new Thread(new ThreadStart(MyThreadProc));
myThread.Name = String.Format("Thread{0}", i + 1);
//Wait a random amount of time before starting next thread.
Thread.Sleep(rnd.Next(0, 1000));
myThread.Start();
}
}
private static void MyThreadProc()
{
for(int i = 0; i < numThreadIterations; i++)
{
UseResource();
//Wait 1 second before next attempt.
Thread.Sleep(1000);
}
}
//A simple method that denies reentrancy.
static bool UseResource()
{
//0 indicates that the method is not in use.
if(0 == Interlocked.Exchange(ref usingResource, 1))
{
Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name);
//Code to access a resource that is not thread safe would go here.
//Simulate some work
Thread.Sleep(500);
Console.WriteLine("{0} exiting lock", Thread.CurrentThread.Name);
//Release the lock
Interlocked.Exchange(ref usingResource, 0);
return true;
}
else
{
Console.WriteLine(" {0} was denied the lock", Thread.CurrentThread.Name);
return false;
}
}
}
}