System.Threading.SpinLock.TryEnter C# (CSharp) Method

TryEnter() public method

public TryEnter ( int millisecondsTimeout, bool &lockTaken ) : void
millisecondsTimeout int
lockTaken bool
return void
        public void TryEnter(int millisecondsTimeout, ref bool lockTaken)
        {
            if (millisecondsTimeout < -1)
                throw new ArgumentOutOfRangeException ("milliSeconds", "millisecondsTimeout is a negative number other than -1");
            if (lockTaken)
                throw new ArgumentException ("lockTaken", "lockTaken must be initialized to false");
            if (isThreadOwnerTrackingEnabled && IsHeldByCurrentThread)
                throw new LockRecursionException ();

            long start = millisecondsTimeout == -1 ? 0 : sw.ElapsedMilliseconds;
            bool stop = false;

            do {
                while (stallTickets != null && stallTickets.TryRemove (ticket.Value))
                    ++ticket.Value;

                long u = ticket.Users;
                long totalValue = (u << 32) | u;
                long newTotalValue
                    = BitConverter.IsLittleEndian ? (u << 32) | (u + 1) : ((u + 1) << 32) | u;

                RuntimeHelpers.PrepareConstrainedRegions ();
                try {}
                finally {
                    lockTaken = Interlocked.CompareExchange (ref ticket.TotalValue, newTotalValue, totalValue) == totalValue;

                    if (lockTaken) {
                        threadWhoTookLock = Thread.CurrentThread.ManagedThreadId;
                        stop = true;
                    }
                }
            } while (!stop && (millisecondsTimeout == -1 || (sw.ElapsedMilliseconds - start) < millisecondsTimeout));
        }

Same methods

SpinLock::TryEnter ( TimeSpan timeout, bool &lockTaken ) : void
SpinLock::TryEnter ( bool &lockTaken ) : void

Usage Example

		public void SemanticCorrectnessTest ()
		{
			sl = new SpinLock (false);

			bool taken = false;
			bool taken2 = false;

			sl.Enter (ref taken);
			Assert.IsTrue (taken, "#1");
			sl.TryEnter (ref taken2);
			Assert.IsFalse (taken2, "#2");
			sl.Exit ();

			sl.TryEnter (ref taken2);
			Assert.IsTrue (taken2, "#3");
		}
All Usage Examples Of System.Threading.SpinLock::TryEnter