本文整理汇总了C#中System.Threading.SpinWait类的典型用法代码示例。如果您正苦于以下问题:C# SpinWait类的具体用法?C# SpinWait怎么用?C# SpinWait使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SpinWait类属于System.Threading命名空间,在下文中一共展示了SpinWait类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
// Demonstrates:
// SpinWait construction
// SpinWait.SpinOnce()
// SpinWait.NextSpinWillYield
// SpinWait.Count
static void Main(){
bool someBoolean = false;
int numYields = 0;
// First task: SpinWait until someBoolean is set to true
Task t1 = Task.Factory.StartNew(() =>
{
SpinWait sw = new SpinWait();
while (!someBoolean)
{
// The NextSpinWillYield property returns true if
// calling sw.SpinOnce() will result in yielding the
// processor instead of simply spinning.
if (sw.NextSpinWillYield) numYields++;
sw.SpinOnce();
}
// As of .NET Framework 4: After some initial spinning,
// SpinWait.SpinOnce() will yield every time.
Console.WriteLine("SpinWait called {0} times, yielded {1} times",
sw.Count, numYields);
});
// Second task: Wait 100ms, then set someBoolean to true
Task t2 = Task.Factory.StartNew(() =>
{
Thread.Sleep(100);
someBoolean = true;
});
// Wait for tasks to complete
Task.WaitAll(t1, t2);
}
示例2: WaitAnyTest
public void WaitAnyTest()
{
ParallelTestHelper.Repeat (delegate {
int flag = 0;
int finished = 0;
InitWithDelegate(delegate {
int times = Interlocked.Exchange (ref flag, 1);
if (times == 1) {
SpinWait sw = new SpinWait ();
while (finished == 0) sw.SpinOnce ();
} else {
Interlocked.Increment (ref finished);
}
});
int index = Task.WaitAny(tasks);
Assert.IsTrue (flag == 1, "#1");
Assert.AreEqual (1, finished, "#2");
Assert.AreNotEqual (-1, index, "#3");
Task.WaitAll (tasks);
});
}
示例3: ExclusiveLock
public static void ExclusiveLock(int lockId, Action method)
{
try
{
var spinWait = new SpinWait();
while (true)
{
int updVal = Interlocked.CompareExchange(ref currentlyHeldLockId, lockId, 0);
if (0 != updVal) break;
spinWait.SpinOnce();
}
exclusiveLockActive = true;
if (currentlyHeldLockId == lockId)
method();
}
finally
{
exclusiveLockActive = false;
if (currentlyHeldLockId == lockId)
currentlyHeldLockId = 0;
}
}
示例4: ExecuteThreadSafeOnce
public bool ExecuteThreadSafeOnce()
{
if (state == Initialized)
{
return false;
}
var inProgressByThisThread = Thread.CurrentThread.ManagedThreadId;
var preexistingState = Interlocked.CompareExchange(ref state, inProgressByThisThread, NotInitialized);
if (preexistingState == NotInitialized)
{
return true;
}
if (preexistingState == Initialized || preexistingState == inProgressByThisThread)
{
return false;
}
#if DOTNET40
var spinWait = new SpinWait();
while (state != Initialized)
{
spinWait.SpinOnce();
}
#else
while (state != Initialized)
{
Thread.SpinWait(5);
}
#endif
return false;
}
示例5: RunSpinWaitTests
public static void RunSpinWaitTests()
{
SpinWait spinner = new SpinWait();
spinner.SpinOnce();
Assert.Equal(spinner.Count, 1);
}
示例6: SpinLock
public SpinLock (bool trackId)
{
this.isThreadOwnerTrackingEnabled = trackId;
this.threadWhoTookLock = 0;
this.lockState = isFree;
this.sw = new SpinWait();
}
示例7: EnterWriteLock
public bool EnterWriteLock(bool block)
{
var start = HiResTimer.Now();
#if DEBUG
if (m_lastWriteThreadID == Thread.CurrentThread.ManagedThreadId)
throw new SynchronizationLockException("Write lock already owned by you");
#endif
var sw = new SpinWait();
do
{
// If there are no readers or writers, grab the write lock.
var state = m_state;
if (state == 0 &&
Interlocked.CompareExchange(ref m_state, MASK_WRITER_BIT, state) == state)
{
#if DEBUG
m_lastWriteThreadID = Thread.CurrentThread.ManagedThreadId;
if (sw.Count > _spinThreshold)
Debug.Print("EnterWriteLock: {0} spins ({1:F1}ms)", sw.Count, HiResTimer.ToTimeSpan(HiResTimer.Now() - start).TotalMilliseconds);
#endif
#if DEBUG_ReaderWriterSpinLock
if (ID != 0)
Debug.Print("{0} Enter Write on #{1} ({2})", Thread.CurrentThread.ManagedThreadId, ID, m_lastWriteThreadID);
#endif
return true;
}
sw.SpinOnce();
}
while (block);
return false;
}
示例8: WaitFor
/// <summary>
/// Wait for the given sequence to be available with a timeout specified.
/// </summary>
/// <param name="sequence">sequence to be waited on.</param>
/// <param name="cursor">cursor on which to wait.</param>
/// <param name="dependents">dependents further back the chain that must advance first</param>
/// <param name="barrier">barrier the processor is waiting on.</param>
/// <param name="timeout">timeout value to abort after.</param>
/// <returns>the sequence that is available which may be greater than the requested sequence.</returns>
/// <exception cref="AlertException">AlertException if the status of the Disruptor has changed.</exception>
public long WaitFor(long sequence, Sequence cursor, Sequence[] dependents, ISequenceBarrier barrier, TimeSpan timeout)
{
long availableSequence;
var spinWait = new SpinWait();
var sw = Stopwatch.StartNew();
if (dependents.Length == 0)
{
while ((availableSequence = cursor.Value) < sequence) // volatile read
{
barrier.CheckAlert();
spinWait.SpinOnce();
if (sw.Elapsed > timeout)
{
break;
}
}
}
else
{
while ((availableSequence = Util.GetMinimumSequence(dependents)) < sequence)
{
barrier.CheckAlert();
spinWait.SpinOnce();
if (sw.Elapsed > timeout)
{
break;
}
}
}
return availableSequence;
}
示例9: WaitUntil
public void WaitUntil(Func<bool> test)
{
SpinWait sw = new SpinWait();
int count = 0;
do
{
sw.SpinOnce();
if (test())
return;
} while (!sw.NextSpinWillYield || ++count < 4);
int? effect = null;
try
{
try {} finally
{
effect = Interlocked.Increment(ref _lockers);
}
lock (this)
{
while (!test())
Monitor.Wait(this);
}
}
finally
{
if (effect.HasValue)
Interlocked.Decrement(ref _lockers);
}
}
示例10: MeasureThroughput
public void MeasureThroughput()
{
const int sendMessageCount = 2000000;
var senderTransport = CreateAndStartZmqTransport("Abc.Testing.Sender");
var receivedMessageCount = 0;
var receiverTransport = CreateAndStartZmqTransport("Abc.Testing.Receiver", _ => ++receivedMessageCount);
var receivers = new[] { new Peer(receiverTransport.PeerId, receiverTransport.InboundEndPoint) };
var transportMessage = new FakeCommand(42).ToTransportMessage();
senderTransport.Send(transportMessage, receivers);
var spinWait = new SpinWait();
while (receivedMessageCount != 1)
spinWait.SpinOnce();
using (Measure.Throughput(sendMessageCount))
{
for (var i = 0; i < sendMessageCount; ++i)
{
senderTransport.Send(transportMessage, receivers);
}
while (receivedMessageCount != sendMessageCount + 1)
spinWait.SpinOnce();
}
senderTransport.Stop();
receiverTransport.Stop();
}
示例11: TryEnterLock
//SpinWait 每20次会有一次系统时间片切换
//清理数据(挂的时候数据一致性是问题,全部删掉)
//然后相当于获取锁往下执行
//测试发现Count=10w时,wait时间为5s
private void TryEnterLock()
{
SpinWait wait = new SpinWait();
int head = *_head;
int tail = *_tail;
int count = 0;
while (Interlocked.CompareExchange(ref *_lck, 1, 0) != 0)
{
wait.SpinOnce();
count++;
if (head != *_head || tail != *_tail)
{
head = *_head;
tail = *_tail;
count = 0;
}
if (count > 100000)
{
Console.WriteLine("ClearData");
_ms.ClearData();
break;
}
}
}
示例12: Enter
public void Enter()
{
//如果调用线程已拥有锁,递增递归计数并返回
Int32 threadId = Thread.CurrentThread.ManagedThreadId;
if (threadId == m_owningThreadId) { m_recursion++; return; }
//调用线程不拥有锁,尝试获取它
SpinWait spinwait = new SpinWait();
for (Int32 spincount = 0; spincount < m_spincount; spincount++)
{
//如果锁可以自由使用,这个线程就获得它:设置一些状态并返回
if (Interlocked.CompareExchange(ref m_waiters, 1, 0) == 0) goto GotLock;
//Black magic:给其它线程运行的机会,希望锁会释放。
spinwait.SpinOnce();
}
//自旋(Spinning)结束,锁仍然没有获得,再试一次
if (Interlocked.Increment(ref m_waiters) > 1)
{
//其它线程阻塞,这个线程也必须阻塞
m_waiterlock.WaitOne();//等待锁:性能损失
//等这个线程醒来时,它拥有锁:设置一些状态并返回。
}
GotLock:
//一个线程拥有锁时,我们记录它的ID,并
//指出线程拥有锁一次
m_owningThreadId = threadId; m_recursion = 1;
}
示例13: InternalSend
protected void InternalSend(ISocketSession session, IList<ArraySegment<byte>> segments)
{
if (!session.CanSend())
return;
if (InternalTrySend(session, segments))
return;
var sendTimeOut = m_SendTimeOut;
//Don't retry, timeout directly
if (sendTimeOut < 0)
{
throw new TimeoutException("The sending attempt timed out");
}
var timeOutTime = sendTimeOut > 0 ? DateTime.Now.AddMilliseconds(sendTimeOut) : DateTime.Now;
var spinWait = new SpinWait();
while (session.CanSend())
{
spinWait.SpinOnce();
if (InternalTrySend(session, segments))
return;
//If sendTimeOut = 0, don't have timeout check
if (sendTimeOut > 0 && DateTime.Now >= timeOutTime)
{
throw new TimeoutException("The sending attempt timed out");
}
}
}
示例14: Wait
/// <summary>
/// Wait Event State to Set
/// </summary>
public void Wait() {
if(IsDebugEnabled)
log.Debug("Wait event state to SET...");
var spinWait = new System.Threading.SpinWait();
var spinCount = 0;
while(_state == UN_SET) {
if(spinCount++ < SpinCount) {
spinWait.SpinOnce();
if(_eventObj == null) {
var mre = new ManualResetEvent(_state == SET);
if(Interlocked.CompareExchange(ref _eventObj, mre, null) != null) {
// If someone set the flag before seeing the new event object, we must ensure it's been set.
if(_state == SET)
_eventObj.Set();
// Lost the race w/ another thread. Just use its event.
else
mre.Close();
}
if(_eventObj != null)
_eventObj.WaitOne();
}
}
}
}
示例15: StartNext
public void StartNext(CompletionLink next) {
var spinner = new SpinWait();
while (!current._RestartWith(next)) {
spinner.SpinOnce();
}
next._Start();
current = next;
}