• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# SpinWait类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中SpinWait的典型用法代码示例。如果您正苦于以下问题:C# SpinWait类的具体用法?C# SpinWait怎么用?C# SpinWait使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



SpinWait类属于命名空间,在下文中一共展示了SpinWait类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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


示例16: SendWithTimeout

        public static int SendWithTimeout(this ZmqSocket socket, byte[] buffer, int length, TimeSpan timeout)
        {
            var stopwatch = Stopwatch.StartNew();
            var spinWait = new SpinWait();
            int result;
            do
            {
                result = socket.Send(buffer, length, SocketFlags.DontWait);
                if (socket.SendStatus != SendStatus.TryAgain)
                    break;

                spinWait.SpinOnce();
            }
            while (stopwatch.Elapsed <= timeout);

            return result;
        }
开发者ID:MarouenK,项目名称:Zebus,代码行数:17,代码来源:ZmqUtil.cs


示例17: SpinWaitForCondition

 public static bool SpinWaitForCondition(Func<bool> predicate, int timeout)
 {
     Thread.MemoryBarrier();
     var sw = new Stopwatch();
     var spin = new SpinWait();
     sw.Start();
     while (sw.ElapsedMilliseconds < timeout)
     {
         if (predicate())
         {
             sw.Stop();
             return true;
         }
         spin.SpinOnce();
     }
     sw.Stop();
     return false;
 }
开发者ID:AlonAmsalem,项目名称:ServiceBlocks,代码行数:18,代码来源:SpinWaitHelper.cs


示例18: ConsumeItems

        protected override void ConsumeItems( int count )
        {
            SpinWait spinWait = new SpinWait();
            int value;

            for ( int i = 0; i < count; )
            {
                if ( this.queue.TryDequeue( out value ) )
                {
                    i++;

                    spinWait.Reset();
                }
                else
                {
                    spinWait.SpinOnce();
                }
            }
        }
开发者ID:postsharp,项目名称:ThreadingTalk,代码行数:19,代码来源:TestSystemConcurrentQueue.cs


示例19: EnterWriteLock

		public void EnterWriteLock()
		{
			SpinWait sw = new SpinWait();
			do
			{
				int state = rwlock;
				if (state < RwWrite)
				{
					if (Interlocked.CompareExchange(ref rwlock, RwWrite, state) == state)
						return;
					state = rwlock;
				}
				// We register our interest in taking the Write lock (if upgradeable it's already done)
				while ((state & RwWait) == 0 && Interlocked.CompareExchange(ref rwlock, state | RwWait, state) != state)
					state = rwlock;
				// Before falling to sleep
				while (rwlock > RwWait)
					sw.SpinOnce();
			} while (true);
		}
开发者ID:925coder,项目名称:ravendb,代码行数:20,代码来源:SimpleRwLock.cs


示例20: EnterReadLock

		public void EnterReadLock (ref bool taken)
		{
			if (taken)
				throw new ArgumentException ("taken", "taken needs to be set to false");

			SpinWait sw = new SpinWait ();
			bool cont = true;

			do {
				while ((rwlock & (RwWrite | RwWait)) > 0)
					sw.SpinOnce ();

				try {}
				finally {
					if ((Interlocked.Add (ref rwlock, RwRead) & (RwWait | RwWait)) == 0) {
						taken = true;
						cont = false;
					} else {
						Interlocked.Add (ref rwlock, -RwRead);
					}
				}
			} while (cont);
		}
开发者ID:nlhepler,项目名称:mono,代码行数:23,代码来源:ReaderWriterLockSlimmer.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Spine类代码示例发布时间:2022-05-24
下一篇:
C# SpinCallback类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap