本文整理汇总了C#中SpinWait类的典型用法代码示例。如果您正苦于以下问题:C# SpinWait类的具体用法?C# SpinWait怎么用?C# SpinWait使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SpinWait类属于命名空间,在下文中一共展示了SpinWait类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Wait
public bool Wait(TimeSpan timeout)
{
SpinWait s = new SpinWait();
bool waitResult = true;
while (m_state == 0)
{
if (s.Spin() >= s_spinCount)
{
if (m_eventObj == null)
{
ManualResetEvent newEvent =
new ManualResetEvent(m_state == 1);
if (Interlocked.CompareExchange<EventWaitHandle>(
ref m_eventObj, newEvent, null) == null)
{
// If someone set the flag before seeing the new
// event obj, we must ensure it’s been set.
if (m_state == 1)
m_eventObj.Set();
}
else
{
// Lost the race w/ another thread. Just use
// its event.
newEvent.Close();
}
}
waitResult = m_eventObj.WaitOne(timeout);
}
}
return waitResult;
}
示例2: Run
public static void Run()
{
var queue = new ConcurrentQueue<int>();
// begin
var producer = Task.Run(() =>
{
foreach (var value in Enumerable.Range(1, 10000))
{
queue.Enqueue(value);
}
});
var consumer = Task.Run(() =>
{
var spinWait = new SpinWait();
var value = 0;
while (value != 10000)
{
if (!queue.TryDequeue(out value))
{
spinWait.SpinOnce();
continue;
}
Logger.Log("Value: {0}", value);
}
});
Task.WaitAll(producer, consumer);
// end
}
示例3: Clear
public void Clear()
{
lock (clearLock)
{
isSend = false;
if (sendDataQueue.Count > 0)
{
SendData cmd;
if (!sendDataQueue.TryDequeue(out cmd))
{
SpinWait spinWait = new SpinWait();
while (sendDataQueue.TryDequeue(out cmd))
{
spinWait.SpinOnce();
}
}
}
if (InterimPacketBuffer != null)
{
Session.Pool.FixedBufferPool.Push(InterimPacketBuffer);
InterimPacketBuffer = null;
}
while (ReceiveBuffers.Count > 0)
{
var packetBuffer = ReceiveBuffers.Dequeue();
Session.Pool.FixedBufferPool.Push(packetBuffer);
}
}
SendBuffer.Clear();
NoComplateCmd = null;
alreadyReceivePacketLength = 0;
needReceivePacketLenght = 0;
}
示例4: SlowEnter
internal bool SlowEnter (StCancelArgs cargs)
{
int lastTime = (cargs.Timeout != Timeout.Infinite) ? Environment.TickCount : 0;
StWaitBlock wb = null;
do {
int sc = spinCount;
#if NET_4_0
var spinWait = new SpinWait ();
#endif
do {
if (state == FREE &&
Interlocked.CompareExchange (ref state, BUSY, FREE) == FREE) {
return true;
}
if (top != null || sc-- <= 0) {
break;
}
#if NET_4_0
spinWait.SpinOnce ();
#else
Thread.SpinWait (1);
#endif
} while (true);
if (wb == null) {
wb = new StWaitBlock (1);
} else {
wb.parker.Reset ();
}
do {
StWaitBlock t;
wb.next = t = top;
if (Interlocked.CompareExchange (ref top, wb, t) == t) {
break;
}
} while (true);
if (TryEnter ()) {
wb.parker.SelfCancel ();
return true;
}
int ws = wb.parker.Park (cargs);
if (ws != StParkStatus.Success) {
cargs.ThrowIfException (ws);
return false;
}
if (TryEnter ()) {
return true;
}
if (!cargs.AdjustTimeout (ref lastTime)) {
return false;
}
} while (true);
}
示例5: Enter
public void Enter() {
// If calling thread already owns the lock, increment recursion count and return
Int32 threadId = Thread.CurrentThread.ManagedThreadId;
if (threadId == m_owningThreadId) { m_recursion++; return; }
// The calling thread doesn't own the lock, try to get it
SpinWait spinwait = new SpinWait();
for (Int32 spinCount = 0; spinCount < m_spincount; spinCount++) {
// If the lock was free, this thread got it; set some state and return
if (Interlocked.CompareExchange(ref m_waiters, 1, 0) == 0) goto GotLock;
// Black magic: give other threads a chance to run
// in hopes that the lock will be released
spinwait.SpinOnce();
}
// Spinning is over and the lock was still not obtained, try one more time
if (Interlocked.Increment(ref m_waiters) > 1) {
// Still contention, this thread must wait
m_waiterLock.WaitOne(); // Wait for the lock; performance hit
// When this thread wakes, it owns the lock; set some state and return
}
GotLock:
// When a thread gets the lock, we record its ID and
// indicate that the thread owns the lock once
m_owningThreadId = threadId; m_recursion = 1;
}
示例6: ParticipateUntil
public void ParticipateUntil (Func<bool> predicate)
{
SpinWait sw = new SpinWait ();
while (!predicate ())
sw.SpinOnce ();
}
示例7: RunSpinWaitTests
public static void RunSpinWaitTests()
{
SpinWait spinner = new SpinWait();
spinner.SpinOnce();
Assert.Equal(spinner.Count, 1);
}
示例8: PowerRegulator
public PowerRegulator()
{
_Sample = 1.0f;
_SpinWait = new SpinWait();
_SpinCount = 0;
_WorkCount = 0;
_Busy = 0;
_TimeCount = new TimeCounter();
_FPS = new FPSCounter();
}
示例9: ParallelForTestCase
public void ParallelForTestCase ()
{
ParallelTestHelper.Repeat (() => {
int[] expected = Enumerable.Range (1, 1000).Select ((e) => e * 2).ToArray ();
int[] actual = Enumerable.Range (1, 1000).ToArray ();
SpinWait sw = new SpinWait ();
Parallel.For (0, actual.Length, (i) => { actual[i] *= 2; sw.SpinOnce (); });
CollectionAssert.AreEquivalent (expected, actual, "#1, same");
CollectionAssert.AreEqual (expected, actual, "#2, in order");
});
}
示例10: SpinUntil
public static bool SpinUntil (Func<bool> condition, int millisecondsTimeout)
{
SpinWait sw = new SpinWait ();
Watch watch = Watch.StartNew ();
while (!condition ()) {
if (watch.ElapsedMilliseconds > millisecondsTimeout)
return false;
sw.SpinOnce ();
}
return true;
}
示例11: run
private void run(CancellationToken token)
{
var list = new List<Entry>(_maxBatchSize);
Logger.Info("[StorageWriter] Entering main loop. {0}", _maxBatchSize);
var spinWait = new SpinWait();
while (token.IsCancellationRequested == false)
{
try
{
while (list.Count < _maxBatchSize)
{
Entry entry;
if (_queue.TryDequeue(out entry) == false)
{
break;
}
Logger.Debug("[StorageWriter] Got something to write...");
if (entry.ShouldDrop())
{
Logger.Debug("[StorageWriter] Dropping message....too old.");
entry.Harikiri();
}
else
list.Add(entry);
}
if (list.Count > 0)
{
store(list.ToArray());
list.Clear();
}
else
{
spinWait.SpinOnce();
}
}
catch (Exception e)
{
Logger.Warn("[StorageWriter] Error in mainloop.", e);
}
_spinwait.SpinOnce();
}
Logger.Info("[StorageWriter] Exiting. No more spinning for me today...");
}
示例12: EnterReadLock
public void EnterReadLock()
{
SpinWait sw = new SpinWait();
do
{
while ((rwlock & (RwWrite | RwWait)) > 0)
sw.SpinOnce();
if ((Interlocked.Add(ref rwlock, RwRead) & (RwWait | RwWait)) == 0)
return;
Interlocked.Add(ref rwlock, -RwRead);
} while (true);
}
示例13: SpinUntil
/// <summary>在指定条件得到满足或指定超时过期之前自旋。</summary>
/// <returns>如果条件在超时时间内得到满足,则为 true;否则为 false</returns>
/// <param name="condition">在返回 true 之前重复执行的委托。</param>
/// <param name="millisecondsTimeout">等待的毫秒数,或为 <see cref="F:System.Threading.Timeout.Infinite" /> (-1),表示无限期等待。</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="condition" /> 参数为 null。</exception>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout" /> 是一个非 -1 的负数,而 -1 表示无限期超时。</exception>
public static bool SpinUntil(Func<bool> condition, int millisecondsTimeout)
{
if (millisecondsTimeout < -1) throw new ArgumentOutOfRangeException("millisecondsTimeout");
if (condition == null) throw new ArgumentNullException("condition");
long ticks = 0;
if (millisecondsTimeout != 0 && millisecondsTimeout != -1) ticks = DateTime.UtcNow.Ticks;
SpinWait wait = new SpinWait();
while (!condition())
{
if (millisecondsTimeout == 0) return false;
wait.SpinOnce();
if (millisecondsTimeout != -1 && wait.NextSpinWillYield && millisecondsTimeout <= (DateTime.UtcNow.Ticks - ticks) / 10000) return false;
}
return true;
}
示例14: LoopWork
/// <summary>
/// 循环工作
/// </summary>
private static void LoopWork()
{
var spinWait = new SpinWait();
while (true)
{
lock (syncRoot)
{
foreach (var item in actions)
{
item.Invoke();
}
}
spinWait.SpinOnce();
}
}
示例15: Dequeue
public override Event Dequeue()
{
Event result = null;
SpinWait spinWait = new SpinWait();
while (!closing)
{
if (queue.TryDequeue(out result))
{
break;
}
spinWait.SpinOnce();
}
return result;
}