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


C# SpinWait.SpinOnce方法代码示例

本文整理汇总了C#中System.Threading.SpinWait.SpinOnce方法的典型用法代码示例。如果您正苦于以下问题:C# SpinWait.SpinOnce方法的具体用法?C# SpinWait.SpinOnce怎么用?C# SpinWait.SpinOnce使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Threading.SpinWait的用法示例。


在下文中一共展示了SpinWait.SpinOnce方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: 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();
        }
开发者ID:MarouenK,项目名称:Zebus,代码行数:31,代码来源:ZmqTransportPerformanceTests.cs

示例2: 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();
                    }
                }
            }
        }
开发者ID:debop,项目名称:NFramework,代码行数:31,代码来源:ThinEvent.cs

示例3: 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);
			});
		}
开发者ID:TheRealDuckboy,项目名称:mono-soc-2008,代码行数:25,代码来源:TaskTest.cs

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

示例5: 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;
            }
        }
开发者ID:hpavlov,项目名称:occurec,代码行数:25,代码来源:NonBlockingLock.cs

示例6: RunSpinWaitTests

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

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

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

示例8: 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;
		}
开发者ID:jmuralimohanbabu,项目名称:Castle.Windsor,代码行数:30,代码来源:ThreadSafeInit.cs

示例9: 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;
        }
开发者ID:TimGebhardt,项目名称:Disruptor-net,代码行数:45,代码来源:SleepingWaitStrategy.cs

示例10: 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);
     }
 }
开发者ID:wizardbeard,项目名称:Shielded,代码行数:29,代码来源:StampLocker.cs

示例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;
                }
            }
        }
开发者ID:huoxudong125,项目名称:HQF.Tutorial.MMF,代码行数:31,代码来源:MMFMessageQueue.cs

示例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;
        }
开发者ID:twfx7758,项目名称:LearnDemo,代码行数:30,代码来源:AnthorHybridLock.cs

示例13: StartNext

 public void StartNext(CompletionLink next) {
    var spinner = new SpinWait();
    while (!current._RestartWith(next)) {
       spinner.SpinOnce();
    }
    next._Start();
    current = next;
 }
开发者ID:ItzWarty,项目名称:the-dargon-project,代码行数:8,代码来源:CompletionLink.cs

示例14: UpgradeToWrite

        /// <summary>
        /// read lock must be aquired prior to calling this!!! we do not check it !!!!
        /// </summary>
        public void UpgradeToWrite()
        {
            var w = new SpinWait();

            while (1 != Interlocked.CompareExchange(ref _lock, _writerLock + 1, 1))
            {
                w.SpinOnce();
            }
        }
开发者ID:yonglehou,项目名称:ReaderWriterLockTiny,代码行数:12,代码来源:ReaderWriterLockTiny.cs

示例15: Wait

        public void Wait()
        {
            SpinWait wait = new SpinWait();

            wait.SpinOnce();

            while (Count > 0)
                Thread.Sleep(1);
        }
开发者ID:ZhenghaiYe,项目名称:iveely,代码行数:9,代码来源:Countdown.cs


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