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


C# SemaphoreSlim.WaitAsync方法代码示例

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


在下文中一共展示了SemaphoreSlim.WaitAsync方法的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: DownloadImages

        public async Task DownloadImages(string mainWallpaperDir, List<PWImage> imageList, Action<PWImage, string> SetupProgress, TaskScheduler scheduler)
        {
            var downloads = new List<Task>();

            SemaphoreSlim semaphore = new SemaphoreSlim(15);
            foreach (var image in imageList)
            {
                await semaphore.WaitAsync();
                var localImage = image;
                var path = Path.Combine(mainWallpaperDir, localImage.Theme.Name, localImage.imageName);
                

                downloads.Add(DownloadImage(image, path, SetupProgress, () => semaphore.Release(), scheduler));

            }
            if(downloads.Any())
                await Task.WhenAll(downloads);
        }
开发者ID:TheAngryByrd,项目名称:ThePaperWallDownloaded,代码行数:18,代码来源:AsyncDownloadManager.cs

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

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

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

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

示例7: GetWithRetryAsync

		public static async Task<HttpResponseMessage> GetWithRetryAsync(this HttpClient client, string url, SemaphoreSlim semaphore, params int[] retryDelay)
		{
			if (retryDelay.Any(delay => delay <= 0))
			{
				throw new ArgumentException("Delay should be greate than 0.", nameof(retryDelay));
			}

			await semaphore.WaitAsync();
			try
			{
				int retryCount = 0;
				while (true)
				{
					try
					{
						return await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
					}
					catch (TaskCanceledException)
					{
						if (retryCount >= retryDelay.Length)
						{
							throw;
						}
					}
					await Task.Delay(retryDelay[retryCount]);
					retryCount++;
				}
			}
			finally
			{
				semaphore.Release();
			}
		}
开发者ID:zhangz,项目名称:Toolbox,代码行数:33,代码来源:HttpClientExtensions.cs

示例8: AcquireAuthorizationAsync

 public async Task<AuthorizationResult> AcquireAuthorizationAsync(Uri authorizationUri, Uri redirectUri, IDictionary<string, string> additionalHeaders, CallState callState)
 {
     returnedUriReady = new SemaphoreSlim(0);
     Authenticate(authorizationUri, redirectUri, additionalHeaders, callState);
     await returnedUriReady.WaitAsync().ConfigureAwait(false);
     return authorizationResult;
 }
开发者ID:AzureAD,项目名称:microsoft-authentication-library-for-dotnet,代码行数:7,代码来源:WebUI.cs

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

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

示例11: ProducerShouldReportCorrectAmountOfAsyncRequests

        public async Task ProducerShouldReportCorrectAmountOfAsyncRequests()
        {
            // var log = new ConsoleLog(); for (int i = 0; i < 100; i++) {
            var semaphore = new SemaphoreSlim(0);
            var routerProxy = new FakeBrokerRouter();
            //block the second call returning from send message async
            routerProxy.BrokerConn0.ProduceResponseFunction = async () =>
            {
                await semaphore.WaitAsync();
                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);

                await 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));
                await Task.Delay(2);
                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.");
                // } log.DebugFormat(i.ToString());
            }
        }
开发者ID:pooyasoleimany,项目名称:KafkaNetClient,代码行数:32,代码来源:ProducerTests.cs

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

示例13: AcquireAuthorizationAsync

 public async Task<AuthorizationResult> AcquireAuthorizationAsync(Uri authorizationUri, Uri redirectUri, CallState callState)
 {
     returnedUriReady = new SemaphoreSlim(0);
     Authenticate(authorizationUri, redirectUri, callState);
     await returnedUriReady.WaitAsync();
     return authorizationResult;
 }
开发者ID:varunpsr,项目名称:XamarinAzureAD,代码行数:7,代码来源:WebUI.cs

示例14: ExecuteAsync

        public override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(this._bucketName))
            {
                throw new InvalidOperationException("The bucketName specified is null or empty!");
            }

            SemaphoreSlim asyncThrottler = null;
            CancellationTokenSource internalCts = null;
            try
            {
                asyncThrottler = new SemaphoreSlim(_config.ConcurrentServiceRequests);
                internalCts = new CancellationTokenSource();
                var internalCancellationToken = internalCts.Token;

                ListMultipartUploadsResponse listResponse = new ListMultipartUploadsResponse();
                var pendingTasks = new List<Task<AbortMultipartUploadResponse>>();
                do
                {
                    ListMultipartUploadsRequest listRequest = ConstructListMultipartUploadsRequest(listResponse);
                    listResponse = await this._s3Client.ListMultipartUploadsAsync(listRequest, cancellationToken)
                        .ConfigureAwait(continueOnCapturedContext: false);

                    foreach (MultipartUpload upload in listResponse.MultipartUploads)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        if (internalCancellationToken.IsCancellationRequested)
                        {
                            // Operation cancelled as one of the AbortMultipartUpload requests failed with an exception,
                            // don't schedule any more AbortMultipartUpload tasks. 
                            // Don't throw an OperationCanceledException here as we want to process the 
                            // responses and throw the original exception.
                            break;
                        }
                        if (upload.Initiated < this._initiatedDate)
                        {
                            await asyncThrottler.WaitAsync(cancellationToken)
                                .ConfigureAwait(continueOnCapturedContext: false);

                            var abortRequest = ConstructAbortMultipartUploadRequest(upload);
                            var task = AbortAsync(abortRequest, internalCts, cancellationToken, asyncThrottler);
                            pendingTasks.Add(task);
                        }
                    }
                }
                while (listResponse.IsTruncated);

                await WhenAllOrFirstExceptionAsync(pendingTasks,cancellationToken)
                    .ConfigureAwait(continueOnCapturedContext: false);
            }
            finally
            {
                if (internalCts != null)
                    internalCts.Dispose();

                if (asyncThrottler!=null)
                    asyncThrottler.Dispose();
            }
        }
开发者ID:rajdotnet,项目名称:aws-sdk-net,代码行数:59,代码来源:AbortMultipartUploadsCommand.async.cs

示例15: TakeAsync

		public static async Task<SemaphoreLock> TakeAsync(SemaphoreSlim semaphore)
		{
			Argument.ValidateIsNotNull(semaphore, "semaphore");

			await semaphore.WaitAsync();

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


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