当前位置: 首页>>代码示例>>C#>>正文


C# SpinWait类代码示例

本文整理汇总了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;
 }
开发者ID:egil,项目名称:Inversion-of-Block-Tridiagonal-Matrices,代码行数:32,代码来源:ThinEvent.cs

示例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
        }
开发者ID:Abc-Arbitrage,项目名称:Abc.NCrafts.Quiz,代码行数:31,代码来源:Answer1.cs

示例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;
 }
开发者ID:luohuazhiyu,项目名称:sunsocket,代码行数:33,代码来源:TcpPacketProtocol.cs

示例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);
		}
开发者ID:duarten,项目名称:mono,代码行数:60,代码来源:StLock.cs

示例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;
    }
开发者ID:ppatoria,项目名称:SoftwareDevelopment,代码行数:28,代码来源:SimpleHybridLock1.cs

示例6: ParticipateUntil

		public void ParticipateUntil (Func<bool> predicate)
		{
			SpinWait sw = new SpinWait ();
			
			while (!predicate ())
				sw.SpinOnce ();
		}
开发者ID:TheRealDuckboy,项目名称:mono-soc-2008,代码行数:7,代码来源:SchedulerProxy.cs

示例7: RunSpinWaitTests

        public static void RunSpinWaitTests()
        {
            SpinWait spinner = new SpinWait();

            spinner.SpinOnce();
            Assert.Equal(spinner.Count, 1);
        }
开发者ID:ESgarbi,项目名称:corefx,代码行数:7,代码来源:SpinWaitTests.cs

示例8: PowerRegulator

 public PowerRegulator()
 {
     _Sample = 1.0f;
     _SpinWait = new SpinWait();
     _SpinCount = 0;
     _WorkCount = 0;
     _Busy = 0;
     _TimeCount = new TimeCounter();
     _FPS = new FPSCounter();
 }
开发者ID:jiowchern,项目名称:Regulus,代码行数:10,代码来源:PowerRegulator.cs

示例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");
			});
		}
开发者ID:calumjiao,项目名称:Mono-Class-Libraries,代码行数:13,代码来源:ParallelTests.cs

示例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;
		}
开发者ID:Indifer,项目名称:Test,代码行数:13,代码来源:SpinWait.cs

示例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...");
        }
开发者ID:heartysoft,项目名称:res,代码行数:50,代码来源:StorageWriter.cs

示例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);
		}
开发者ID:925coder,项目名称:ravendb,代码行数:14,代码来源:SimpleRwLock.cs

示例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;
 }
开发者ID:g992com,项目名称:esb,代码行数:21,代码来源:SpinWait.cs

示例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();
     }
 }
开发者ID:cityjoy,项目名称:NetworkSocket,代码行数:18,代码来源:LoopWorker.cs

示例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;
        }
开发者ID:jaykang920,项目名称:x2clr,代码行数:16,代码来源:ConcurrentEventQueue.cs


注:本文中的SpinWait类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。