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


C# SemaphoreSlim.Release方法代码示例

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


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

示例1: ParallelLoadGames

        private const int GameCacheDuration = 43200; // 12 hours

        public async Task<GameDetails[]> ParallelLoadGames(IEnumerable<int> gameIds)
        {
            GameDetails[] results;
            var tasks = new List<Task<GameDetails>>();
            using (var throttler = new SemaphoreSlim(5))
            {
                foreach (var gameId in gameIds)
                {
                    await throttler.WaitAsync();
                    tasks.Add(Task<GameDetails>.Run(async () =>
                    {
                        try
                        {
                            Debug.WriteLine("Loading {0}...", gameId);
                            return await this.LoadGame(gameId, true);
                        }
                        finally
                        {
                            Debug.WriteLine("Done with {0}...", gameId);
                            throttler.Release();
                        }
                    }));

                }
                results = await Task.WhenAll(tasks);
            }
            return results;
        }
开发者ID:vfportero,项目名称:bgg-json,代码行数:30,代码来源:BoardGameGeekClient.cs

示例2: 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

示例3: 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

示例4: SemaphoreSlimLock

		public async Task SemaphoreSlimLock()
		{
			var _lock = new SemaphoreSlim( 1 );
			await _lock.WaitAsync();
			_lock.Release();

			var start = Stopwatch.GetTimestamp();
			for( var i = 0; i < Iterations; i++ ) {
				await _lock.WaitAsync();
				_lock.Release();
					i--;
					i++;
			}
			ReportTime( start );
		}
开发者ID:yonglehou,项目名称:AsyncLock,代码行数:15,代码来源:SingleThreadTests.cs

示例5: 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

示例6: 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

示例7: Authorize

        public async Task<TokenPair> Authorize(string clientId, string clientSecret, IEnumerable<string> scopes)
        {
            string uri = string.Format("/LoginPage.xaml?authEndpoint={0}&clientId={1}&scope={2}",
                                       authEndpoint,
                                       clientId,
                                       string.Join(" ", scopes));

            SemaphoreSlim semaphore = new SemaphoreSlim(0, 1);

            Observable.FromEvent<NavigatingCancelEventHandler, NavigatingCancelEventArgs>(
                h => new NavigatingCancelEventHandler(h),
                h => this.frame.Navigating += h,
                h => this.frame.Navigating -= h)
                      .SkipWhile(h => h.EventArgs.NavigationMode != NavigationMode.Back)
                      .Take(1)
                      .Subscribe(e => semaphore.Release());

            frame.Navigate(new Uri(uri, UriKind.Relative));

            await semaphore.WaitAsync();

            string authorizationCode = (string)PhoneApplicationService.Current.State["OAuth_Demo.AuthorizationCode"];

            return await RequestAccessToken(authorizationCode, clientId, clientSecret);
        }
开发者ID:praveenmohanmm,项目名称:PurposeColor_Bkp_Code,代码行数:25,代码来源:OAuthAuthorization.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: EnsureList

        /// <summary>
        /// Ensures the list.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="file">The file.</param>
        /// <param name="httpClient">The HTTP client.</param>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="semaphore">The semaphore.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        public static async Task EnsureList(string url, string file, IHttpClient httpClient, IFileSystem fileSystem, SemaphoreSlim semaphore, CancellationToken cancellationToken)
        {
            var fileInfo = fileSystem.GetFileInfo(file);

            if (!fileInfo.Exists || (DateTime.UtcNow - fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays > 1)
            {
                await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);

                try
                {
                    var temp = await httpClient.GetTempFile(new HttpRequestOptions
                    {
                        CancellationToken = cancellationToken,
                        Progress = new Progress<double>(),
                        Url = url

                    }).ConfigureAwait(false);

					fileSystem.CreateDirectory(Path.GetDirectoryName(file));

					fileSystem.CopyFile(temp, file, true);
                }
                finally
                {
                    semaphore.Release();
                }
            }
        }
开发者ID:paul-777,项目名称:Emby,代码行数:38,代码来源:ImageUtils.cs

示例10: 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

示例11: Execute

        public void Execute(IJobExecutionContext context) {
            var stopwatch = new Stopwatch();
            stopwatch.Start();

            Logger.Info("开始抓取一号店数据");

            var downloadedCategories = new YhdCategoryExtractor().Extract().Result;
            var needProcessCategories = _CategoryArchiveService.Archive(downloadedCategories).OrderBy(c => c.ProductsUpdateTime);
            
            var taskLock = new SemaphoreSlim(initialCount: 1);
            var tasks = needProcessCategories.Select(async (category, index) => {
                await taskLock.WaitAsync();
                try {
                    var result = await ProcessCategoryAsync(category);
                    //■◆▲●□◇△○
                    Logger.Info(string.Join(" ", new[]{
                            string.Format("{0}", index + 1),
                            string.Format("[{0}]{1}", category.Number, category.Name),
                            string.Format("□{0} △{1}", result.Total, result.Changed)
                        }));
                }
                catch (Exception e) {
                    Logger.ErrorFormat("处理分类{0}{1}失败", e, category.Name, category.Number);
                }
                finally {
                    taskLock.Release();
                }
            });

            Task.WaitAll(tasks.ToArray());

            Logger.InfoFormat("抓取一号店数据完成,用时{0:0.#}分", stopwatch.Elapsed.TotalMinutes);
        }
开发者ID:keily,项目名称:LightOne,代码行数:33,代码来源:YhdArchiveJob.cs

示例12: 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

示例13: Consume

        // WIP, not producing useful numbers yet. Assumes one partition.
        public static async Task<long> Consume(string broker, string topic)
        {
            long n = 0;

            var topicConfig = new TopicConfig();
            topicConfig["auto.offset.reset"] = "smallest";
            var config = new Config()
            {
                GroupId = "benchmark-consumer",
                DefaultTopicConfig = topicConfig
            };
            using (var consumer = new EventConsumer(config, broker))
            {
                var signal = new SemaphoreSlim(0, 1);

                consumer.OnMessage += (obj, msg) =>
                {
                    n += 1;
                };

                consumer.OnEndReached += (obj, end) =>
                {
                    Console.WriteLine($"End reached");
                    signal.Release();
                };

                consumer.Subscribe(new List<string>{topic});
                consumer.Start();

                await signal.WaitAsync();
                Console.WriteLine($"Shutting down");
            }

            return n;
        }
开发者ID:yousifh,项目名称:rdkafka-dotnet,代码行数:36,代码来源:Program.cs

示例14: TestCancelWaitAsyncInternal

        private async Task TestCancelWaitAsyncInternal()
        {
            var r = new Random();
            var s = new SemaphoreSlim(1);

            await Task.WhenAll(Enumerable.Range(0, 100).Select(async i =>
            {
                var ct = CancellationToken.None;
                if ((i % 5) == 0)
                {
                    var cts = new CancellationTokenSource();
                    var t = Task.Delay(1).ContinueWith(_ => cts.Cancel());
                    ct = cts.Token;
                }

                try
                {
                    await s.WaitAsync(ct);
                    await Delay(r, ct).ConfigureAwait(false);
                }
                catch (TestException) { }
                catch (OperationCanceledException) { }
                finally
                {
                    s.Release();
                }
            }));
        }
开发者ID:KKubodera,项目名称:MinimumAsyncBridge,代码行数:28,代码来源:UnitTestSemaphoreSlim.cs

示例15: 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


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