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


C# SemaphoreSlim.Wait方法代码示例

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


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

示例1: AsyncLockShouldAllowOnlyOneThread

        public void AsyncLockShouldAllowOnlyOneThread()
        {
            var block = new SemaphoreSlim(0, 2);
            var count = 0;
            var alock = new AsyncLock();

            var firstCall = Task.Factory.StartNew(async () =>
            {
                using (await alock.LockAsync())
                {
                    Interlocked.Increment(ref count);
                    block.Wait();
                }
                block.Wait();//keep this thread busy
            });

            TaskTest.WaitFor(() => count > 0);

            alock.LockAsync().ContinueWith(t => Interlocked.Increment(ref count));

            Assert.That(count, Is.EqualTo(1), "Only one task should have gotten past lock.");
            Assert.That(firstCall.IsCompleted, Is.False, "Task should still be running.");

            block.Release();
            TaskTest.WaitFor(() => count > 1);
            Assert.That(count, Is.EqualTo(2), "Second call should get past lock.");
            Assert.That(firstCall.IsCompleted, Is.False, "First call should still be busy.");
            block.Release();
        }
开发者ID:wenisman,项目名称:simple-kafka-net,代码行数:29,代码来源:AsyncLockTests.cs

示例2: ExtremeDisposal

        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();
            }
        }
开发者ID:RonKillerMan,项目名称:RabbitMQHare,代码行数:29,代码来源:RabbitPublisher.cs

示例3: CancelBeforeWait

        public static void CancelBeforeWait()
        {
            SemaphoreSlim semaphoreSlim = new SemaphoreSlim(2);

            CancellationTokenSource cs = new CancellationTokenSource();
            cs.Cancel();
            CancellationToken ct = cs.Token;

            const int millisec = 100;
            TimeSpan timeSpan = new TimeSpan(100);
            EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(millisec, ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            EnsureOperationCanceledExceptionThrown(() => semaphoreSlim.Wait(timeSpan, ct), ct, "CancelBeforeWait:  An OCE should have been thrown.");
            semaphoreSlim.Dispose();
        }
开发者ID:johnhhm,项目名称:corefx,代码行数:15,代码来源:SemaphoreSlimCancellationTests.cs

示例4: Main

        static void Main(string[] args)
        {
            Console.Write("request count(8 recommanded): ");
            var requestCount = int.Parse(Console.ReadLine());
            ServicePointManager.DefaultConnectionLimit = 10000;
            
            var alert = new AlertInSecond();

            var ss = new SemaphoreSlim(requestCount, requestCount);
            while (true)
            {
                ss.Wait();
                Task.Run(OneRequest).ContinueWith(t =>
                {
                    if (t.Status == TaskStatus.Faulted)
                    {
                        alert.AddOneFail();
                    }
                    else
                    {
                        var response = t.Result;
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            alert.AddOneSuccess();
                        }
                        else
                        {
                            alert.AddOneFail();
                        }
                    }
                    
                    ss.Release();
                });
            }
        }
开发者ID:sdcb,项目名称:fuck-iphone-stealer,代码行数:35,代码来源:Program.cs

示例5: Construct_GivenSemaphoreSlim_ShouldLockIt

        public void Construct_GivenSemaphoreSlim_ShouldLockIt()
        {
            //---------------Set up test pack-------------------
            using (var semaphore = new SemaphoreSlim(1))
            {
                bool? gotLock = null;
                //---------------Assert Precondition----------------
                using (new LenientAutoLocker(semaphore))
                {
                    var barrier = new Barrier(2);
                    Task.Run(() =>
                    {
                        barrier.SignalAndWait();
                        Thread.Sleep(1000);
                        // ReSharper disable once AccessToDisposedClosure
                        gotLock = semaphore.Wait(100);
                    });
                    //---------------Execute Test ----------------------
                    barrier.SignalAndWait();
                    Thread.Sleep(2000);

                    //---------------Test Result -----------------------
                    Assert.IsNotNull(gotLock);
                    Assert.IsFalse(gotLock.Value);
                }
            }
        }
开发者ID:Chillisoft,项目名称:splunk4net,代码行数:27,代码来源:TestLenientAutoLocker.cs

示例6: TryDequeue_IfMustWaitForItem_ThenProvidesItAndReturnsTrue

 public void TryDequeue_IfMustWaitForItem_ThenProvidesItAndReturnsTrue()
 {
     DoTest((q, cts) =>
     {
         using (var willProvideItemAfterSleep = new SemaphoreSlim(0))
         {
             var tasks = new Task[]
                 {
                     new Task(() =>
                         {
                             string item;
                             willProvideItemAfterSleep.Wait();
                             Assert.IsTrue(q.TryDequeue(out item, cts.Token));
                             Assert.AreEqual("7", item);
                         }),
                     new Task(() =>
                         {
                             willProvideItemAfterSleep.Release();
                             Thread.Sleep(500);
                             q.Enqueue(7);
                         })
                 };
             Parallel.ForEach<Task>(tasks, T => T.Start());
             Task.WaitAll(tasks);
         }
     });
 }
开发者ID:RoboJackets,项目名称:Housekeeping,代码行数:27,代码来源:CancellableQueue_UnitTests.cs

示例7: ProducerShouldReportCorrectAmountOfAsyncRequests

        public void ProducerShouldReportCorrectAmountOfAsyncRequests()
        {
            var semaphore = new SemaphoreSlim(0);
            var routerProxy = new FakeBrokerRouter();
            //block the second call returning from send message async
            routerProxy.BrokerConn0.ProduceResponseFunction = () => { semaphore.Wait(); return new ProduceResponse(); };

            var router = routerProxy.Create();
            using (var producer = new Producer(router, maximumAsyncRequests: 1) { BatchSize = 1 })
            {
                var messages = new[] { new Message("1") };

                Assert.That(producer.AsyncCount, Is.EqualTo(0));

                var sendTask = producer.SendMessageAsync(BrokerRouterProxy.TestTopic, messages);

                TaskTest.WaitFor(() => producer.AsyncCount > 0);
                Assert.That(producer.AsyncCount, Is.EqualTo(1), "One async operation should be sending.");

                semaphore.Release();
                sendTask.Wait(TimeSpan.FromMilliseconds(500));

                Assert.That(sendTask.IsCompleted, Is.True, "Send task should be marked as completed.");
                Assert.That(producer.AsyncCount, Is.EqualTo(0), "Async should now show zero count.");
            }
        }
开发者ID:jsifantu,项目名称:kafka-net,代码行数:26,代码来源:ProducerTests.cs

示例8: TaskMain

 private static void TaskMain(SemaphoreSlim semaphore)
 {
     bool isCompleted = false;
     while (!isCompleted)
     {
         if (semaphore.Wait(600))
         {
             try
             {
                 WriteLine($"Task {Task.CurrentId} locks the semaphore");
                 Task.Delay(2000).Wait();
             }
             finally
             {
                 WriteLine($"Task {Task.CurrentId} releases the semaphore");
                 semaphore.Release();
                 isCompleted = true;
             }
         }
         else
         {
             WriteLine($"Timeout for task {Task.CurrentId}; wait again");
         }
     }
 }
开发者ID:ProfessionalCSharp,项目名称:ProfessionalCSharp6,代码行数:25,代码来源:Program.cs

示例9: AwaitingConnectedSpheroRunner

 public AwaitingConnectedSpheroRunner(IStreamSocketWrapper streamSpheroWrapper)
 {
     _streamSpheroWrapper = streamSpheroWrapper;
     _itemsToSendEvent = new SemaphoreSlim(1);
     _itemsToSendEvent.Wait();
     _commandsToSend = new Queue<CommandWithActions>();
 }
开发者ID:jihlee,项目名称:BallControl,代码行数:7,代码来源:AwaitingConnectedSpheroRunner.cs

示例10: Main

    static int Main(string[] args)
    {
        SemaphoreSlim s = new SemaphoreSlim(initialCount: 1);

        var cts = new CancellationTokenSource();
        s.Wait();
        var t = s.WaitAsync(cts.Token);
        s.Release();
        cts.Cancel();


        if (t.Status != TaskStatus.Canceled && s.CurrentCount == 0)
        {
            Console.WriteLine("PASS");
            return 100;
        }
        else
        {
            Console.WriteLine("FAIL");
            Console.WriteLine("Expected task status to not be Canceled and s.CurrentCount == 0");
            Console.WriteLine("Actual: Task: " + t.Status + "; CurrentCount: " + s.CurrentCount);
            return 101;
        }


    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:26,代码来源:test489437.cs

示例11: TaskMain

 static void TaskMain(SemaphoreSlim semaphore)
 {
     bool isCompleted = false;
       while (!isCompleted)
       {
     if (semaphore.Wait(600))
     {
       try
       {
     Console.WriteLine("Task {0} locks the semaphore", Task.CurrentId);
     Thread.Sleep(2000);
       }
       finally
       {
     Console.WriteLine("Task {0} releases the semaphore", Task.CurrentId);
     semaphore.Release();
     isCompleted = true;
       }
     }
     else
     {
       Console.WriteLine("Timeout for task {0}; wait again",
      Task.CurrentId);
     }
       }
 }
开发者ID:CNinnovation,项目名称:ParallelProgrammingFeb2016,代码行数:26,代码来源:Program.cs

示例12: DeclareAndUseIt

        public void DeclareAndUseIt()
        {
            var channel = this.Connection.CreateChannel();
            var exchange = channel.DeclareExchange("my6exchange", new ExchangeOptions()
            {
                // using default options = ephemeral
                ExchangeType = RabbitExchangeType.Fanout
            });

            var queue1 = exchange.DeclareQueue("q1", new QueueOptions());
            var queue2 = exchange.DeclareQueue("q2", new QueueOptions());
            var wait = new SemaphoreSlim(2, 2);
            var receivedCount = 0;

            queue1.Consume(new Action<MessageEnvelope<MyDumbMessage>>(env =>
            {
                wait.Release();
                Interlocked.Increment(ref receivedCount);
            }), new ConsumerOptions());
            queue2.Consume(new Action<MessageEnvelope<MyDumbMessage>>(env =>
            {
                wait.Release();
                Interlocked.Increment(ref receivedCount);
            }), new ConsumerOptions());

            exchange.Send(new MyDumbMessage()); // message will be dropped

            wait.Wait(TimeSpan.FromSeconds(2.0));

            receivedCount.Should().Be(2);
        }
开发者ID:zhoufoxcn,项目名称:Castle.RabbitMq,代码行数:31,代码来源:_6_PubSubWithFanoutExchange.cs

示例13: CancelAfterWait

        public static bool CancelAfterWait()
        {
            TestHarness.TestLog("* SemaphoreSlimCancellationTests.CancelAfterWait()");
            bool passed = true;

            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            CancellationToken cancellationToken = cancellationTokenSource.Token;

            SemaphoreSlim semaphoreSlim = new SemaphoreSlim(0); // semaphore that will block all waiters
            
            ThreadPool.QueueUserWorkItem(
                (args) =>
                {
                    Thread.Sleep(1000);
                    cancellationTokenSource.Cancel();
                }
                );

            //Now wait.. the wait should abort and an exception should be thrown
            passed &= TestHarnessAssert.EnsureOperationCanceledExceptionThrown(
                () => semaphoreSlim.Wait(cancellationToken),
                cancellationToken, "An OCE(null) should have been thrown that references the cancellationToken.");

            // the token should not have any listeners.
            // currently we don't expose this.. but it was verified manually

            return passed;
        }
开发者ID:modulexcite,项目名称:IL2JS,代码行数:28,代码来源:SemaphoreSlimCancellationTests.cs

示例14: RunAndBlock

        private static void RunAndBlock(int threadCount)
        {
            ProfilerStart();
            _Semaphore = new SemaphoreSlim(threadCount, threadCount);

            var queue = new QueueClient();

            while (!_Cancel)
            {
                _Semaphore.Wait();
                var solicutud = queue.GetNextMessage();
                if (solicutud == null)
                {
                    Thread.Sleep(millisecondsTimeout: _NoMessageFoundSleepTimeoutMsec);
                }
                else
                {
                    var t = new Thread(new ParameterizedThreadStart(RunThreaded));
                    t.Start(solicutud);
                }
            }
            //Pause();

            // release threads
            ProfilerStop();
        }
开发者ID:c0ns0le,项目名称:scripts-4,代码行数:26,代码来源:Program.cs

示例15: Take

		public static SemaphoreLock Take(SemaphoreSlim semaphore)
		{
			Argument.ValidateIsNotNull(semaphore, "semaphore");

			semaphore.Wait();

			return new SemaphoreLock(semaphore);
		}
开发者ID:2a486f72,项目名称:useful,代码行数:8,代码来源:SemaphoreLock.cs


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