System.Threading.SemaphoreSlim.Wait C# (CSharp) Method

Wait() public method

public Wait ( int millisecondsTimeout ) : bool
millisecondsTimeout int
return bool
		public bool Wait (int millisecondsTimeout)
		{
			CheckState ();
			if (millisecondsTimeout < -1)
				throw new ArgumentOutOfRangeException ("millisecondsTimeout",
				                                       "millisecondsTimeout is a negative number other than -1");
			if (millisecondsTimeout == -1) {
				Wait ();
				return true;
			}
			
			do {
				int result = Interlocked.Decrement (ref currCount);
				if (result >= 0)
					break;
				
				// We revert back the operation
				result = Interlocked.Increment (ref currCount);
				Watch sw = Watch.StartNew ();
				while (Thread.VolatileRead (ref currCount) <= 0) {
					if (sw.ElapsedMilliseconds > millisecondsTimeout) {
						sw.Stop ();
						return false;
					}
					wait.SpinOnce ();
				}
			} while (true);
			
			return true;
		}
		

Same methods

SemaphoreSlim::Wait ( System.TimeSpan ts ) : bool
SemaphoreSlim::Wait ( ) : void

Usage Example

        public void ExtremeDisposal()
        {
            using (var context = CreateContext())
            {
                Assert.AreEqual(-1, context.Publisher.MySettings.MaxConnectionRetry, "For this test, we want the worst situation");

                context.Publisher.Start(0);
                Assert.IsTrue(context.Publisher.Started);

                var message = new byte[] { 0, 1, 1 };
                var connectionFail = new SemaphoreSlim(0);
                context.Model.Setup(m => m.BasicPublish(It.IsAny<string>(), It.IsAny<string>(), context.Publisher.Props, message)).Throws(new Exception("I don't want your message anymore"));
                context.Connection.Setup(c => c.CreateModel()).Callback(() => connectionFail.Release(1)).Throws(new Exception("And I don't want to accept your connection either"));

                context.Publisher.Publish("test", message);

                /* The way callbacks are implemented on exception throwing mocks does not garantee
                 * that the callback is called "after" the exception is thrown.
                 * If we wait for two, we are sure at least one has been finished !
                 */
                Assert.IsTrue(connectionFail.Wait(1000));
                Assert.IsTrue(connectionFail.Wait(1000));

                context.Publisher.Dispose();
                context.Publisher = null; //to avoid the double dispose of Publisher
                //The real test here is that eventually the Dispose method returns
                Assert.Pass();
            }
        }
All Usage Examples Of System.Threading.SemaphoreSlim::Wait