System.Threading.Tasks.Task.WhenAll(params System.Threading.Tasks.Task[])

Here are the examples of the csharp api System.Threading.Tasks.Task.WhenAll(params System.Threading.Tasks.Task[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

3691 Examples 7

19 View Source File : BlockchainServiceExtensions.cs
License : MIT License
Project Creator : AElfProject

public static async Task<List<BlockWithTransactions>> GetBlocksWithTransactionsAsync(this IBlockchainService blockchainService,
            Hash firstHash, int count)
        {
            var blocks = await blockchainService.GetBlocksInBestChainBranchAsync(firstHash, count);
            
            var list = blocks
                .Select(async block =>
                {
                    var transactions = await blockchainService.GetTransactionsAsync(block.TransactionIds);
                    return new BlockWithTransactions { Header = block.Header, Transactions = { transactions } };
                });

            return (await Task.WhenAll(list)).ToList();
        }

19 View Source File : UserStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public override async Task<IList<string>> GetRolesAsync(TUser user, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            replacedertNotNull(user, nameof(user));

            Dictionary<string, TUserRole> userRoles;
            try
            {
                var response = await _client.GetAsync<Dictionary<string, TUserRole>>(GetFirebasePath(UserRolesTableName), cancellationToken, false, $"orderBy=\"UserId\"&equalTo=\"{user.Id}\"")
                    .ConfigureAwait(false);
                userRoles = response.Data;
            }
            catch (FirebaseException e)
                when (e.FirebaseError != null && e.FirebaseError.Error.StartsWith("Index"))
            {
                await _userOnlyStore.SetIndex(UserRolesTableName, new UseRoleIndex(), cancellationToken)
                    .ConfigureAwait(false);

                var response = await _client.GetAsync<Dictionary<string, TUserRole>>(GetFirebasePath(UserRolesTableName), cancellationToken, false, $"orderBy=\"UserId\"&equalTo=\"{user.Id}\"")
                    .ConfigureAwait(false);
                userRoles = response.Data;
            }


            if (userRoles != null)
            {
                var concurrentBag = new ConcurrentBag<string>();
                var taskList = new List<Task>(userRoles.Count);

                foreach(var userRole in userRoles.Values)
                {
                    taskList.Add(GetUserRoleAsync(userRole, concurrentBag, cancellationToken));
                }

                await Task.WhenAll(taskList.ToArray())
                    .ConfigureAwait(false);

                return concurrentBag.ToList();
            }
            return new List<string>(0);
        }

19 View Source File : JobServerQueue.cs
License : MIT License
Project Creator : actions

public async Task ShutdownAsync()
        {
            if (!_queueInProcess)
            {
                Trace.Info("No-op, all queue process tasks have been stopped.");
            }

            Trace.Info("Fire signal to shutdown all queues.");
            _jobCompletionSource.TrySetResult(0);

            await Task.WhenAll(_allDequeueTasks);
            _queueInProcess = false;
            Trace.Info("All queue process task stopped.");

            // Drain the queue
            // ProcessWebConsoleLinesQueueAsync() will never throw exception, live console update is always best effort.
            Trace.Verbose("Draining web console line queue.");
            await ProcessWebConsoleLinesQueueAsync(runOnce: true);
            Trace.Info("Web console line queue drained.");

            // ProcessFilesUploadQueueAsync() will never throw exception, log file upload is always best effort.
            Trace.Verbose("Draining file upload queue.");
            await ProcessFilesUploadQueueAsync(runOnce: true);
            Trace.Info("File upload queue drained.");

            // ProcessTimelinesUpdateQueueAsync() will throw exception during shutdown
            // if there is any timeline records that failed to update contains output variabls.
            Trace.Verbose("Draining timeline update queue.");
            await ProcessTimelinesUpdateQueueAsync(runOnce: true);
            Trace.Info("Timeline update queue drained.");

            Trace.Info("All queue process tasks have been stopped, and all queues are drained.");
        }

19 View Source File : JobDispatcherHostedService.cs
License : MIT License
Project Creator : AdemCatamak

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            List<Task> tasks = new List<Task>();
            for (var i = 0; i < _concurrentExecutionCount; i++)
            {
                Task task = Task.Run(async () => { await InfiniteBackgroundJob(stoppingToken); }, stoppingToken);
                tasks.Add(task);
            }

            await Task.WhenAll(tasks.ToArray());
        }

19 View Source File : GoToDeclarationOrHandlerCommand.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private async Task CommandCallbackAsync()
		{
			IWpfTextView textView = await ServiceProvider.GetWpfTextViewAsync();

			if (textView == null || Package.DisposalToken.IsCancellationRequested)
				return;

			SnapshotPoint caretPosition = textView.Caret.Position.BufferPosition;
			ITextSnapshotLine caretLine = caretPosition.GetContainingLine();

			if (caretLine == null)
				return;

			Doreplacedent doreplacedent = caretPosition.Snapshot.GetOpenDoreplacedentInCurrentContextWithChanges();
			if (doreplacedent == null || Package.DisposalToken.IsCancellationRequested)
				return;

			Task<SyntaxNode> syntaxRootTask = doreplacedent.GetSyntaxRootAsync();
			Task<SemanticModel> semanticModelTask = doreplacedent.GetSemanticModelAsync();
			await Task.WhenAll(syntaxRootTask, semanticModelTask);

			#pragma warning disable VSTHRD002, VSTHRD103 // Avoid problematic synchronous waits - the results are already obtained
			SyntaxNode syntaxRoot = syntaxRootTask.Result;
			SemanticModel semanticModel = semanticModelTask.Result;
			#pragma warning restore VSTHRD002, VSTHRD103

			if (syntaxRoot == null || semanticModel == null)
				return;

			TextSpan lineSpan = TextSpan.FromBounds(caretLine.Start.Position, caretLine.End.Position);

			if (!(syntaxRoot.FindNode(lineSpan) is MemberDeclarationSyntax memberNode))
				return;

			PXContext context = new PXContext(semanticModel.Compilation, Areplacedinator.Utilities.CodereplacedysisSettings.Default);

			if (!context.IsPlatformReferenced || Package.DisposalToken.IsCancellationRequested)
				return;

			ISymbol memberSymbol = GetMemberSymbol(memberNode, semanticModel, caretPosition);

			if (memberSymbol == null || !CheckMemberSymbol(memberSymbol, context))
				return;

			await NavigateToHandlerOrDeclarationAsync(doreplacedent, textView, memberSymbol, memberNode, semanticModel, context);
		}

19 View Source File : RunnerServer.cs
License : MIT License
Project Creator : actions

public async Task ConnectAsync(Uri serverUrl, VssCredentials credentials)
        {
            var createGenericConnection = EstablishVssConnection(serverUrl, credentials, TimeSpan.FromSeconds(100));
            var createMessageConnection = EstablishVssConnection(serverUrl, credentials, TimeSpan.FromSeconds(60));
            var createRequestConnection = EstablishVssConnection(serverUrl, credentials, TimeSpan.FromSeconds(60));

            await Task.WhenAll(createGenericConnection, createMessageConnection, createRequestConnection);

            _genericConnection = await createGenericConnection;
            _messageConnection = await createMessageConnection;
            _requestConnection = await createRequestConnection;

            _genericTaskAgentClient = _genericConnection.GetClient<TaskAgentHttpClient>();
            _messageTaskAgentClient = _messageConnection.GetClient<TaskAgentHttpClient>();
            _requestTaskAgentClient = _requestConnection.GetClient<TaskAgentHttpClient>();

            _hasGenericConnection = true;
            _hasMessageConnection = true;
            _hasRequestConnection = true;
        }

19 View Source File : FixAllContextHelper.cs
License : Apache License 2.0
Project Creator : agoda-com

public static async Task<ImmutableDictionary<Doreplacedent, ImmutableArray<Diagnostic>>> GetDoreplacedentDiagnosticsToFixAsync(FixAllContext fixAllContext)
        {
            var allDiagnostics = ImmutableArray<Diagnostic>.Empty;
            var projectsToFix = ImmutableArray<Project>.Empty;

            var doreplacedent = fixAllContext.Doreplacedent;
            var project = fixAllContext.Project;

            switch (fixAllContext.Scope)
            {
                case FixAllScope.Doreplacedent:
                    if (doreplacedent != null)
                    {
                        var doreplacedentDiagnostics = await fixAllContext.GetDoreplacedentDiagnosticsAsync(doreplacedent).ConfigureAwait(false);
                        return ImmutableDictionary<Doreplacedent, ImmutableArray<Diagnostic>>.Empty.Sereplacedem(doreplacedent, doreplacedentDiagnostics);
                    }

                    break;

                case FixAllScope.Project:
                    projectsToFix = ImmutableArray.Create(project);
                    allDiagnostics = await GetAllDiagnosticsAsync(fixAllContext, project).ConfigureAwait(false);
                    break;

                case FixAllScope.Solution:
                    projectsToFix = project.Solution.Projects
                        .Where(p => p.Language == project.Language)
                        .ToImmutableArray();

                    var diagnostics = new ConcurrentDictionary<ProjectId, ImmutableArray<Diagnostic>>();
                    var tasks = new Task[projectsToFix.Length];
                    for (var i = 0; i < projectsToFix.Length; i++)
                    {
                        fixAllContext.CancellationToken.ThrowIfCancellationRequested();
                        var projectToFix = projectsToFix[i];
                        tasks[i] = Task.Run(
                            async () =>
                            {
                                var projectDiagnostics = await GetAllDiagnosticsAsync(fixAllContext, projectToFix).ConfigureAwait(false);
                                diagnostics.TryAdd(projectToFix.Id, projectDiagnostics);
                            }, fixAllContext.CancellationToken);
                    }

                    await Task.WhenAll(tasks).ConfigureAwait(false);
                    allDiagnostics = allDiagnostics.AddRange(diagnostics.SelectMany(i => i.Value.Where(x => fixAllContext.DiagnosticIds.Contains(x.Id))));
                    break;
            }

            if (allDiagnostics.IsEmpty)
            {
                return ImmutableDictionary<Doreplacedent, ImmutableArray<Diagnostic>>.Empty;
            }

            return await GetDoreplacedentDiagnosticsToFixAsync(allDiagnostics, projectsToFix, fixAllContext.CancellationToken).ConfigureAwait(false);
        }

19 View Source File : ValidationBehaviour.cs
License : MIT License
Project Creator : Abdulrhman5

public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
        {
            if (_validators.Any())
            {
                var context = new ValidationContext<TRequest>(request);

                var validationResults = await Task.WhenAll(_validators.Select(v => v.ValidateAsync(context, cancellationToken)));
                var failures = validationResults.SelectMany(r => r.Errors).Where(f => f != null).ToList();
                
                if (failures.Count != 0)
                    throw new ValidationException(failures);
            }
            return await next();
        }

19 View Source File : UserOnlyStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public async override Task<IList<TUser>> GetUsersForClaimAsync(Claim claim, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            replacedertNotNull(claim, nameof(claim));

            Dictionary<string, TUserClaim> data;
            try
            {
                var response = await _client.GetAsync<Dictionary<string, TUserClaim>>(GetFirebasePath(UserClaimsTableName), cancellationToken, false, $"orderBy=\"ClaimType\"&equalTo=\"{claim.Type}\"")
                    .ConfigureAwait(false);
                data = response.Data;
            }
            catch (FirebaseException e)
                when (e.FirebaseError != null && e.FirebaseError.Error.StartsWith("Index"))
            {
                await SetIndex(UserClaimsTableName, new UserClaimIndex(), cancellationToken)
                    .ConfigureAwait(false);

                var response = await _client.GetAsync<Dictionary<string, TUserClaim>>(GetFirebasePath(UserClaimsTableName), cancellationToken, queryString: $"orderBy=\"ClaimType\"&equalTo=\"{claim.Type}\"")
                    .ConfigureAwait(false);
                data = response.Data;
            }

            if (data == null)
            {
                return new List<TUser>(0);
            }

            var userIds = data.Values.Where(c => c.ClaimValue == claim.Value).Select(c => c.UserId);
            var users = new ConcurrentBag<TUser>();
            var taskList = new List<Task>(userIds.Count());
            foreach (var userId in userIds)
            {
                taskList.Add(Task.Run(async () => {
                    var user = await FindByIdAsync(userId, cancellationToken)
                        .ConfigureAwait(false);
                    if (user != null)
                    {
                        users.Add(user);
                    }
                }));
            }

            await Task.WhenAll(taskList.ToArray())
                .ConfigureAwait(false);

            return users.ToList();
        }

19 View Source File : TippingModule.cs
License : MIT License
Project Creator : acid-chicken

[Command("balance"), Summary("残高を表示します。"), Alias("残高")]
        public async Task BalanceAsync([Remainder] string comment = null)
        {
            var account = TippingManager.GetAccountName(Context.User);
            var address = await TippingManager.EnsureAccountAsync(account).ConfigureAwait(false);
            var earned = decimal.Zero;
            await Task.WhenAll(TippingManager.GetCollection().Find(x => x.To == Context.User.Id).Select(async x =>
            {
                try
                {
                    earned += x.Amount;
                    var from = DiscordClient.GetUser(x.From);
                    var txid = await TippingManager.InvokeMethodAsync("sendfrom", TippingManager.GetAccountName(from), address, x.Amount).ConfigureAwait(false);
                    var isDeleted = await TippingManager.DeleteRequestAsync(x.Id).ConfigureAwait(false);
                    await RequestLogAsync(new LogMessage(LogSeverity.Verbose, "TippingModule", $"Sent {x.Amount} ZNY from {from.Username}#{from.Discriminator} to {Context.User.Username}#{Context.User.Discriminator}."));
                }
                catch (Exception ex)
                {
                    await RequestLogAsync(new LogMessage(LogSeverity.Error, "TippingModule", ex.Message, ex));
                }
            }));
            var balance0 = decimal.Parse(await TippingManager.InvokeMethodAsync("getbalance", account, 0).ConfigureAwait(false));
            var balance1 = decimal.Parse(await TippingManager.InvokeMethodAsync("getbalance", account, 1).ConfigureAwait(false));
            var queued = TippingManager.GetCollection().Find(x => x.From == Context.User.Id).Sum(x => x.Amount);
            await ReplyAsync
            (
                message: Context.User.Mention,
                embed:
                    new EmbedBuilder()
                        .Withreplacedle("残高")
                        .WithDescription($"{balance0} ZNY")
                        .WithCurrentTimestamp()
                        .WithColor(Colors.Blue)
                        .WithFooter(EmbedManager.CurrentFooter)
                        .WithAuthor(Context.User)
                        .AddInlineField("利用可能", $"{balance1 - queued:N8} ZNY")
                        .AddInlineField("検証待ち", $"{balance0 - balance1:N8} ZNY")
                        .AddInlineField("受取待ち", $"{queued:N8} ZNY")
                        .AddInlineField("受け取り", $"{earned:N8} ZNY")
            ).ConfigureAwait(false);
        }

19 View Source File : FileLoggerContext.cs
License : MIT License
Project Creator : adams85

public Task GetCompletion(IServiceProvider serviceProvider)
        {
            return Task.WhenAll(GetProviders(serviceProvider).Select(provider => provider.Completion));
        }

19 View Source File : AdamantCompiler.cs
License : MIT License
Project Creator : adamant

public async Task<PackageIL> CompilePackageAsync(
            Name name,
            IEnumerable<ICodeFileSource> fileSources,
            FixedDictionary<Name, Task<PackageIL>> referenceTasks,
            TaskScheduler taskScheduler)
        {
            var lexer = new Lexer();
            var parser = new CompilationUnitParser();
            var parseBlock = new TransformBlock<ICodeFileSource, ICompilationUnitSyntax>(
                async (fileSource) =>
                {
                    var file = await fileSource.LoadAsync().ConfigureAwait(false);
                    var context = new ParseContext(file, new Diagnostics());
                    var tokens = lexer.Lex(context).WhereNotTrivia();
                    return parser.Parse(tokens);
                }, new ExecutionDataflowBlockOptions()
                {
                    TaskScheduler = taskScheduler,
                    EnsureOrdered = false,
                });

            foreach (var fileSource in fileSources)
                parseBlock.Post(fileSource);

            parseBlock.Complete();

            await parseBlock.Completion.ConfigureAwait(false);

            if (!parseBlock.TryReceiveAll(out var compilationUnits))
                throw new Exception("Not all compilation units are ready");

            var referencePairs = await Task
                                       .WhenAll(referenceTasks.Select(async kv =>
                                           (alias: kv.Key, package: await kv.Value.ConfigureAwait(false))))
                                       .ConfigureAwait(false);
            var references = referencePairs.ToFixedDictionary(r => r.alias, r => r.package);

            // TODO add the references to the package syntax
            var packageSyntax = new PackageSyntax(name, compilationUnits.ToFixedSet(), references);

            var replacedyzer = new Semanticreplacedyzer()
            {
                SaveLivenessreplacedysis = SaveLivenessreplacedysis,
                SaveReachabilityGraphs = SaveReachabilityGraphs,
            };

            return replacedyzer.Check(packageSyntax);
        }

19 View Source File : TippingManager.cs
License : MIT License
Project Creator : acid-chicken

public static async Task WorkAsync(CancellationToken token = default)
        {
            while (!token.IsCancellationRequested)
            {
                await Task.WhenAll
                (
                    RequestLogAsync(new LogMessage(LogSeverity.Verbose, "TippingManager", "Calling tasks.")),
                    CheckRequestsAsync(),
                    Task.Delay(60000)
                ).ConfigureAwait(false);
            }
        }

19 View Source File : LocalParallelTransactionExecutingService.cs
License : MIT License
Project Creator : AElfProject

private async Task<ExecutionReturnSetMergeResult> ExecuteParallelizableTransactionsAsync(
            List<List<Transaction>> groupedTransactions, BlockHeader blockHeader, BlockStateSet blockStateSet,
            CancellationToken cancellationToken)
        {
            var tasks = groupedTransactions.Select(
                txns => ExecuteAndPreprocessResult(new TransactionExecutingDto
                {
                    BlockHeader = blockHeader,
                    Transactions = txns,
                    PartialBlockStateSet = blockStateSet
                }, cancellationToken));
            var results = await Task.WhenAll(tasks);
            Logger.LogTrace("Executed parallelizables.");

            var executionReturnSets = MergeResults(results, out var conflictingSets);
            Logger.LogTrace("Merged results from parallelizables.");
            return new ExecutionReturnSetMergeResult
            {
                ExecutionReturnSets = executionReturnSets,
                ConflictingReturnSets = conflictingSets
            };
        }

19 View Source File : SimCluster.cs
License : MIT License
Project Creator : abdullin

public Task StopServices(Predicate<ServiceId> selector = null, TimeSpan? grace = null) {
            var tasks = Filter(selector).Select(p => p.Stop(grace ?? 2.Sec())).ToArray();
            if (tasks.Length == 0) {
                throw new ArgumentException("No services match selector", nameof(selector));
            }
            
            return Task.WhenAll(tasks);
        }

19 View Source File : LogEventProcessorTests.cs
License : MIT License
Project Creator : AElfProject

[Fact]
        public async Task ProcessAsync_Test()
        {
            var chain = await _smartContractExecutionHelper.CreateChainAsync();
            var block = await _blockchainService.GetBlockByHashAsync(chain.BestChainHash);
            var tasks = block.Body.TransactionIds
                .Select(t => _transactionResultQueryService.GetTransactionResultAsync(t)).ToList();
            var transactionResultList = await Task.WhenAll(tasks);

            await ProcessTransactionResultsAsync(transactionResultList, block);

            var transaction = new Transaction
            {
                From = _smartContractAddressService.GetZeroSmartContractAddress(),
                To = _smartContractAddressService.GetZeroSmartContractAddress(),
                MethodName = nameof(ACS0Container.ACS0Stub.DeploySmartContract),
                Params = new ContractDeploymentInput
                {
                    Category = KernelConstants.DefaultRunnerCategory,
                    Code = ByteString.CopyFrom(
                        _smartContractExecutionHelper.ContractCodes["AElf.Contracts.Mulreplacedoken"])
                }.ToByteString()
            };
            var blockExecutedSet = await _smartContractExecutionHelper.ExecuteTransactionAsync(transaction);
            
            await ProcessTransactionResultsAsync(blockExecutedSet.TransactionResultMap.Values.ToArray(), blockExecutedSet.Block);

            await ProcessCodeUpdateAsync(chain);
        }

19 View Source File : DocumentApiClientTest.cs
License : Apache License 2.0
Project Creator : Actify-Inc

[Fact]
        public async Task DeleteDoreplacedents_ShouldSucceed_WhenOldDoreplacedentOptionIsSelected()
        {
            var docTasks = new[] {
                new Dictionary<string, object> { ["Message"] = "first" },
                new Dictionary<string, object> { ["Message"] = "second" }
            }
            .Select(item => _docClient.PostDoreplacedentAsync(_testCollection, item))
            .ToList();

            PostDoreplacedentResponse<Dictionary<string, object>>[] docs =
                await Task.WhenAll(docTasks);

            replacedert.Collection(docs,
                (item) => replacedert.NotNull(item._id),
                (item) => replacedert.NotNull(item._id));

            var response = await _docClient.DeleteDoreplacedentsAsync<MyTestClreplaced>(
                _testCollection,
                docs.Select(d => d._id).ToList(),
                new DeleteDoreplacedentsQuery
                {
                    ReturnOld = true
                });

            replacedert.Collection(response,
                (item) =>
                {
                    replacedert.NotNull(item._id);
                    replacedert.NotNull(item.Old);
                    replacedert.Equal("first", item.Old.Message);
                },
                (item) =>
                {
                    replacedert.NotNull(item._id);
                    replacedert.NotNull(item.Old);
                    replacedert.Equal("second", item.Old.Message);
                });

            // Should get "not found" for deleted docs
            replacedert.Collection(docs,
                async (item) =>
                {
                    var ex = await replacedert.ThrowsAsync<ApiErrorException>(async () =>
                        await _docClient.GetDoreplacedentAsync<object>(item._id));

                    replacedert.Equal(NOT_FOUND_NUM, ex.ApiError.ErrorNum); // doreplacedent not found)
                },
                async (item) =>
                {
                    var ex = await replacedert.ThrowsAsync<ApiErrorException>(async () =>
                        await _docClient.GetDoreplacedentAsync<object>(item._id));

                    replacedert.Equal(NOT_FOUND_NUM, ex.ApiError.ErrorNum); // doreplacedent not found)
                });
        }

19 View Source File : UserOnlyStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public override async Task AddClaimsAsync(TUser user, IEnumerable<Claim> claims, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            replacedertNotNull(user, nameof(user));
            replacedertNotNull(claims, nameof(claims));

            List<TUserClaim> userClaims = claims.Select(c => CreateUserClaim(user, c)).ToList();
            var taskList = new List<Task>(userClaims.Count);
            foreach(var userClaim in userClaims)
            {
                taskList.Add(_client.PostAsync(GetFirebasePath(UserClaimsTableName), userClaim, cancellationToken));
            }

            await Task.WhenAll(taskList.ToArray())
                .ConfigureAwait(false);
        }

19 View Source File : MpInfoContainer.cs
License : MIT License
Project Creator : 52ABP

public static async Task RegisterAsync(string key, string appId, string appSecret, string token, string encodingAESKey, string name = null, UserKeyType userId = default(UserKeyType), TenantKeyType tenantId = default(TenantKeyType))
        {
            //记录注册信息,RegisterFunc委托内的过程会在缓存丢失之后自动重试

            RegisterFuncCollection[key] = async () =>
            {
                //using (FlushCache.CreateInstance())
                //{
                var bag = new MpInfoBag()
                {
                    Key = key,
                    Name = name,
                    AppId = appId,
                    AppSecret= appSecret,
                    Token = token,
                    EncodingAESKey = encodingAESKey,
                };
                await UpdateAsync(key, bag, null).ConfigureAwait(false);//第一次添加,此处已经立即更新
                return bag;
                //}
            };
            var registerTask = RegisterFuncCollection[key]();

            var updateRegiestListTask = UpdateRegiestList(key, userId, tenantId);
            await Task.WhenAll(new[] { registerTask, updateRegiestListTask });//等待所有任务完成
        }

19 View Source File : UserOnlyStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public async override Task<IList<TUser>> GetUsersForClaimAsync(Claim claim, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            replacedertNotNull(claim, nameof(claim));

            var result = await _db.HashGetAllAsync(UserClaimsKeyPrefix + claim.Type)
                .ConfigureAwait(false);

            var users = new ConcurrentBag<TUser>();
            var taskList = new List<Task>(result.Length);
            foreach (var uc in result)
            {
                taskList.Add(Task.Run(async () => {
                    var user = await FindByIdAsync(uc.Name, cancellationToken)
                        .ConfigureAwait(false);
                    if (user != null)
                    {
                        users.Add(user);
                    }
                }));
            }

            await Task.WhenAll(taskList.ToArray())
                .ConfigureAwait(false);

            return users.ToList();
        }

19 View Source File : DacMissingPrimaryKeyFix.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public async override Task RegisterCodeFixesAsync(CodeFixContext context)
		{
			context.CancellationToken.ThrowIfCancellationRequested();

			var rootTask = context.Doreplacedent.GetSyntaxRootAsync(context.CancellationToken);
			var semanticModelTask = context.Doreplacedent.GetSemanticModelAsync(context.CancellationToken);

			await Task.WhenAll(rootTask, semanticModelTask).ConfigureAwait(false);

			var root = rootTask.Result;
			SemanticModel semanticModel = semanticModelTask.Result;

			if (!(root?.FindNode(context.Span) is ClreplacedDeclarationSyntax dacNode))
				return;

			INamedTypeSymbol dacTypeSymbol = semanticModel?.GetDeclaredSymbol(dacNode, context.CancellationToken);

			if (dacTypeSymbol == null || dacTypeSymbol.MemberNames.Contains(TypeNames.ReferentialIntegrity.PrimaryKeyClreplacedName))
				return;

			var pxContext = new PXContext(semanticModel.Compilation, codereplacedysisSettings: null);

			if (pxContext.ReferentialIntegritySymbols.PrimaryKeyOf == null)
				return;

			var codeActionreplacedle = nameof(Resources.PX1033Fix).GetLocalized().ToString();
			var codeAction = CodeAction.Create(codeActionreplacedle,
											   cancellation => AddPrimaryKeyDeclarationToDacAsync(context.Doreplacedent, root, dacNode, pxContext, 
																								  dacTypeSymbol, cancellation),
											   equivalenceKey: codeActionreplacedle);

			context.RegisterCodeFix(codeAction, context.Diagnostics);
		}

19 View Source File : SuppressDiagnosticCommandBase.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

protected virtual async Task CommandCallbackAsync()
		{		
			IWpfTextView textView = await ServiceProvider.GetWpfTextViewAsync();

			if (textView == null)
				return;

			SnapshotPoint caretPosition = textView.Caret.Position.BufferPosition;
			ITextSnapshotLine caretLine = caretPosition.GetContainingLine();

			if (caretLine == null)
				return;

			Doreplacedent doreplacedent = caretPosition.Snapshot.GetOpenDoreplacedentInCurrentContextWithChanges();
			if (doreplacedent == null || !doreplacedent.SupportsSyntaxTree /*|| doreplacedent.SourceCodeKind ==*/)
				return;

			Task<SyntaxNode> syntaxRootTask = doreplacedent.GetSyntaxRootAsync(Package.DisposalToken);
			Task<SemanticModel> semanticModelTask = doreplacedent.GetSemanticModelAsync(Package.DisposalToken);
			await Task.WhenAll(syntaxRootTask, semanticModelTask);

#pragma warning disable VSTHRD002, VSTHRD103 // Avoid problematic synchronous waits - the results are already obtained
			SyntaxNode syntaxRoot = syntaxRootTask.Result;
			SemanticModel semanticModel = semanticModelTask.Result;
#pragma warning restore VSTHRD002, VSTHRD103

			if (syntaxRoot == null || semanticModel == null || !IsPlatformReferenced(semanticModel) ||
				Package.DisposalToken.IsCancellationRequested)
			{
				return;
			}

			TextSpan caretSpan = GetTextSpanFromCaret(caretPosition, caretLine);
			List<DiagnosticData> diagnosticData = await GetDiagnosticsAsync(doreplacedent, caretSpan);
			SyntaxNode nodeWithDiagnostic = syntaxRoot.FindNode(caretSpan);

			if (nodeWithDiagnostic != null)
			{
				await SuppressDiagnosticsAsync(diagnosticData, doreplacedent, syntaxRoot, semanticModel, nodeWithDiagnostic);
			}
		}

public async Task<TradeSubscribeAck> Subscribe(string tickerSymbol, TradeEventType[] events, IActorRef subscriber)
        {
            var tasks = ToTopics(tickerSymbol, events).Select(x =>
                _mediator.Ask<SubscribeAck>(new Subscribe(x, subscriber), TimeSpan.FromSeconds(3)));

            await Task.WhenAll(tasks).ConfigureAwait(false);

            return new TradeSubscribeAck(tickerSymbol, events);
        }

19 View Source File : RpcTestController.cs
License : MIT License
Project Creator : ad313

[HttpGet]
        public async Task<IActionResult> Get()
        {
            //Parallel.For(0, 100, i =>
            //{
            //    var str = _eventBusProvider.RpcClientAsync<string>("rpc-test1").GetAwaiter().GetResult();
            //    Console.WriteLine(i + "-----" + str);
            //});


            var tasks = Enumerable.Range(0, 10).Select(d => _eventBusProvider.RpcClientAsync<string>("rpc-test1")).ToArray();
            await Task.WhenAll(tasks);

            var str = await _eventBusProvider.RpcClientAsync<string>("rpc-test1");

            return string.IsNullOrWhiteSpace(str.Data) ? BadRequest() : Ok(str.Data);

            return Ok();
        }

19 View Source File : TippingModule.cs
License : MIT License
Project Creator : acid-chicken

[Command("rain"), Summary("条件を満たしたユーザー全員に均等に投げ銭します。端数で総金額が多少変動することがあります。末尾に`powerful`をつけると、総金額ではなく一人あたりに投げ銭される金額を指定したことになります。"), Alias("撒金"), RequireContext(ContextType.Guild | ContextType.Group)]
        public async Task RainAsync([Summary("金額")] decimal totalAmount = decimal.MinusOne, [Remainder] string comment = null)
        {
            if (totalAmount == decimal.MinusOne)
            {
                totalAmount = (decimal)Math.Pow(10, Random.NextDouble()) - 1;
            }
            var targets = await TippingManager.GetUsersAsync(Context.Channel, Context.User, 10).ConfigureAwait(false);
            if (targets.Any())
            {
                var limit = DateTimeOffset.Now.AddDays(3);
                var amount = comment?.ToLower()?.Contains("powerful") ?? false ? totalAmount : Math.Truncate(totalAmount / targets.Count * 10000000) / 10000000;
                var count = targets.Count;
                var embed =
                    new EmbedBuilder()
                        .Withreplacedle("撒き銭完了")
                        .WithDescription("撒き銭しました。DM通知は行われませんのでご注意下さい。")
                        .WithCurrentTimestamp()
                        .WithColor(Colors.Green)
                        .WithFooter(EmbedManager.CurrentFooter)
                        .WithAuthor(Context.User)
                        .AddInlineField("一人あたりの金額", $"{amount:N8} ZNY")
                        .AddInlineField("対象者数", $"{count} 人")
                        .AddInlineField("総金額", $"{amount * count:N8} ZNY");
                if (!string.IsNullOrEmpty(comment))
                {
                    embed = embed.AddField("コメント", comment);
                }
                await Task.WhenAll(targets.Select(x => TippingManager.AddRequestAsync(new TipRequest(Context.User.Id, x.Id, amount, limit))).Append(ReplyAsync
                (
                    message: Context.User.Mention,
                    embed: embed
                ))).ConfigureAwait(false);
            }
            else
            {
                await ReplyAsync
                (
                    message: Context.User.Mention,
                    embed:
                        new EmbedBuilder()
                            .Withreplacedle("撒き銭失敗")
                            .WithDescription("撒き銭に失敗しました。撒き銭対象となれるユーザーがいないか、指定した金額が不正である可能性があります。")
                            .WithCurrentTimestamp()
                            .WithColor(Colors.Red)
                            .WithFooter(EmbedManager.CurrentFooter)
                            .WithAuthor(Context.User)
                ).ConfigureAwait(false);
            }
        }

19 View Source File : Command.cs
License : Apache License 2.0
Project Creator : adamralph

public static async Task<Result> ReadAsync(
            string name,
            string? args = null,
            string? workingDirectory = null,
            string? windowsName = null,
            string? windowsArgs = null,
            Action<IDictionary<string, string>>? configureEnvironment = null,
            Encoding? encoding = null,
            Func<int, bool>? handleExitCode = null,
            string? standardInput = null,
            CancellationToken cancellationToken = default)
        {
            Validate(name);

            using var process = new Process();

            process.StartInfo = ProcessStartInfo.Create(
                RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? windowsName ?? name : name,
                (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? windowsArgs ?? args : args) ?? "",
                workingDirectory ?? "",
                true,
                configureEnvironment ?? defaultAction,
                true,
                encoding);

            var runProcess = process.RunAsync(true, defaultEchoPrefix, cancellationToken);

            Task<string> readOutput;
            Task<string> readError;

            try
            {
                await process.StandardInput.WriteAsync(standardInput).ConfigureAwait(false);
                process.StandardInput.Close();

                readOutput = process.StandardOutput.ReadToEndAsync();
                readError = process.StandardError.ReadToEndAsync();
            }
            catch (Exception)
            {
                await runProcess.ConfigureAwait(false);
                throw;
            }

            await Task.WhenAll(runProcess, readOutput, readError).ConfigureAwait(false);

#pragma warning disable CA1849 // Call async methods when in an async method
            var output = readOutput.Result;
            var error = readError.Result;
#pragma warning restore CA1849 // Call async methods when in an async method

            return (handleExitCode?.Invoke(process.ExitCode) ?? false) || process.ExitCode == 0
                ? new Result(output, error)
                : throw new ExitCodeReadException(process.ExitCode, output, error);
        }

19 View Source File : TargetCollection.cs
License : Apache License 2.0
Project Creator : adamralph

private async Task RunAsync(
            List<Target> targets,
            bool dryRun,
            bool parallel,
            bool skipDependencies,
            Func<Exception, bool> messageOnly,
            Output output)
        {
            await output.Starting(targets).Tax();

            try
            {
                var runningTargets = new Dictionary<Target, Task>();

                using var sync = new SemapreplacedSlim(1, 1);

                if (parallel)
                {
                    var tasks = targets.Select(target => this.RunAsync(target, targets, dryRun, true, skipDependencies, messageOnly, output, runningTargets, sync, rootDependencyPath));
                    await Task.WhenAll(tasks).Tax();
                }
                else
                {
                    foreach (var target in targets)
                    {
                        await this.RunAsync(target, targets, dryRun, false, skipDependencies, messageOnly, output, runningTargets, sync, rootDependencyPath).Tax();
                    }
                }
            }
            catch (Exception)
            {
                await output.Failed(targets).Tax();
                throw;
            }

            await output.Succeeded(targets).Tax();
        }

19 View Source File : TickerManager.cs
License : MIT License
Project Creator : acid-chicken

public static async Task SetGameAsTickerAsync()
        {
            try
            {
                Ticker = await ApiManager.GetTickerAsync("bitzeny", "JPY").ConfigureAwait(false);
                var game = $"[{DateTimeOffset.FromUnixTimeSeconds(long.TryParse(Ticker.LastUpdated ?? "0", out long x) ? x : 0).ToLocalTime():M/d HH:mm}] {(double.TryParse(Ticker.PriceJpy ?? "0", out double y) ? y : 0):N3} JPY (hourly: {(Ticker.PercentChangeOnehour.StartsWith('-') || Ticker.PercentChangeOnehour == "0.00" ? "" : "+")}{Ticker.PercentChangeOnehour}% / daily: {(Ticker.PercentChangeTwentyfourhours.StartsWith('-') || Ticker.PercentChangeTwentyfourhours == "0.00" ? "" : "+")}{Ticker.PercentChangeTwentyfourhours}% / weekly: {(Ticker.PercentChangeSevenDays.StartsWith('-') || Ticker.PercentChangeSevenDays == "0.00" ? "" : "+")}{Ticker.PercentChangeSevenDays}%)";
                await Task.WhenAll
                (
                    DiscordClient.SetGameAsync(game),
                    RequestLogAsync(new LogMessage(LogSeverity.Verbose, "TickerManager", $"Set game to \"{game}\"."))
                ).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                await RequestLogAsync(new LogMessage(LogSeverity.Error, "TickerManager", ex.Message, ex)).ConfigureAwait(false);
            }
        }

19 View Source File : FileLoggerProcessor.cs
License : MIT License
Project Creator : adams85

private async Task ResetCoreAsync(Action onQueuesCompleted, bool complete)
        {
            CancellationTokenSource forcedCompleteTokenSource;
            Task[] completionTasks;

            lock (_logFiles)
            {
                if (_status != Status.Running)
                    return;

                forcedCompleteTokenSource = _forcedCompleteTokenSource;
                _forcedCompleteTokenSource = new CancellationTokenSource();

                completionTasks = _logFiles.Values.Select(async logFile =>
                {
                    logFile.Queue.Writer.Complete();

                    await logFile.WriteFileTask.ConfigureAwait(false);

                    if (logFile.IsOpen)
                        logFile.Close();
                }).ToArray();

                _logFiles.Clear();

                onQueuesCompleted?.Invoke();

                if (complete)
                    _status = Status.Completing;
            }

            try
            {
                var completionTimeoutTask = Task.Delay(Context.CompletionTimeout);
                if ((await Task.WhenAny(Task.WhenAll(completionTasks), completionTimeoutTask).ConfigureAwait(false)) == completionTimeoutTask)
                    Context.ReportDiagnosticEvent(new FileLoggerDiagnosticEvent.QueuesCompletionForced(this));

                forcedCompleteTokenSource.Cancel();
                forcedCompleteTokenSource.Dispose();
            }
            finally
            {
                if (complete)
                    Dispose();
            }
        }

19 View Source File : BackendServer.cs
License : MIT License
Project Creator : abdullin

public Task Run() {
            return Task.WhenAll(EventLoop(), ProjectionThread());
        }

19 View Source File : ManageController.cs
License : MIT License
Project Creator : Adoxio

[HttpGet]
		[ExternalLogin]
		public async Task<ActionResult> ChangeLogin(CancellationToken cancellationToken)
		{
			if (Adxstudio.Xrm.Configuration.PortalSettings.Instance.Ess.IsEss)
			{
				return HttpNotFound();
			}

			var userId = User.Idenreplacedy.GetUserId();
			var user = await UserManager.FindByIdAsync(userId);

			if (user == null)
			{
				throw new ApplicationException("Account error.");
			}

			var id = 0;
			var userLogins = await UserManager.GetLoginsAsync(userId);
			var tasks = AuthenticationManager.GetExternalAuthenticationTypes().Select(p => ToExternalAuthenticationTypes(id++, userLogins, p, cancellationToken));
			var externalAuthenticationTypes = await Task.WhenAll(tasks);

			var logins = externalAuthenticationTypes
				.OrderBy(pair => pair.Provider.Caption)
				.ToList();

			ViewBag.ShowRemoveButton = user.PreplacedwordHash != null || userLogins.Count() > 1;

			var snippets = new SnippetDataAdapter(new PortalConfigurationDataAdapterDependencies());

			var breadcrumbSnippetName = snippets.Select("Profile/SecurityNav/ChangeLogin");
			ViewBag.Pagereplacedle = breadcrumbSnippetName != null ? breadcrumbSnippetName.Value.Value : ResourceManager.GetString("Manage_External_Authentication");

			return View(new ChangeLoginViewModel { Logins = logins });
		}

19 View Source File : DocumentApiClientTest.cs
License : Apache License 2.0
Project Creator : Actify-Inc

[Fact]
        public async Task DeleteDoreplacedents_ShouldSucceed()
        {
            var docTasks = new[] {
                new Dictionary<string, object> { ["Message"] = "first" },
                new Dictionary<string, object> { ["Message"] = "second" }
            }
            .Select(item => _docClient.PostDoreplacedentAsync(_testCollection, item))
            .ToList();

            PostDoreplacedentResponse<Dictionary<string, object>>[] docs =
                await Task.WhenAll(docTasks);

            replacedert.Collection(docs,
                (item) => replacedert.NotNull(item._id),
                (item) => replacedert.NotNull(item._id));

            var response = await _docClient.DeleteDoreplacedentsAsync(_testCollection, docs.Select(d => d._id).ToList());
            replacedert.Collection(response,
                (item) => replacedert.NotNull(item._id),
                (item) => replacedert.NotNull(item._id));

            // Should get "not found" for deleted docs
            replacedert.Collection(docs,
                async (item) =>
                {
                    var ex = await replacedert.ThrowsAsync<ApiErrorException>(async () =>
                        await _docClient.GetDoreplacedentAsync<object>(item._id));

                    replacedert.Equal(NOT_FOUND_NUM, ex.ApiError.ErrorNum); // doreplacedent not found)
                },
                async (item) =>
                {
                    var ex = await replacedert.ThrowsAsync<ApiErrorException>(async () =>
                        await _docClient.GetDoreplacedentAsync<object>(item._id));

                    replacedert.Equal(NOT_FOUND_NUM, ex.ApiError.ErrorNum); // doreplacedent not found)
                });
        }

19 View Source File : BlockDownloadService.cs
License : MIT License
Project Creator : AElfProject

private async Task<bool?> CheckIrreversibleBlockHashAsync(Hash blockHash, long blockHeight)
        {
            var peers = _networkService.GetPeers(false)
                .Where(p => p.SyncState == SyncState.Finished &&
                            p.LastKnownLibHeight >= blockHeight)
                .ToList();

            if (peers.Count < PeerCheckMinimumCount)
            {
                return null;
            }

            var taskList = peers.Select(async peer =>
                await _networkService.GetBlocksAsync(blockHash, 1, peer.Pubkey));

            var hashCheckResult = await Task.WhenAll(taskList);

            var confirmCount = 2 * peers.Count() / 3 + 1;
            var result = hashCheckResult.Where(r => r.Success)
                .GroupBy(a => a.Payload != null && a.Payload.Count == 1)
                .FirstOrDefault(group => group.Count() >= confirmCount);

            return result?.Key;
        }

19 View Source File : AuditoriumSeatingAdapter.cs
License : Apache License 2.0
Project Creator : 42skillz

public async Task<AuditoriumSeating> GetAuditoriumSeating(ShowId showId)
        {
            // Call the AuditoriumLayout Bounded Context in order to get an empty AuditoriumSeating
            var auditoriumDtoTask = _auditoriumLayoutProviderWebClient.GetAuditoriumSeatingFor(showId.Id);

            // Call the SeatReservation Bounded Context to get the list of already reserved seats
            var reservedSeatsDtoTask = _seatsReservationsProviderWebClient.GetReservedSeats(showId.Id);

            await Task.WhenAll(auditoriumDtoTask, reservedSeatsDtoTask);

            var auditoriumDto = auditoriumDtoTask.Result;
            var reservedSeatsDto = reservedSeatsDtoTask.Result;

            // Adapt all these information into a type belonging to our SeatSuggestion Bounded Context (External Domains/BCs INFRA => Our Domain)
            var auditoriumSeating = AdaptAuditoriumSeatingDto(auditoriumDto, reservedSeatsDto);

            return auditoriumSeating;
        }

19 View Source File : GrpcNetworkServer.cs
License : MIT License
Project Creator : AElfProject

private async Task DialBootNodesAsync()
        {
            if (NetworkOptions.BootNodes == null || !NetworkOptions.BootNodes.Any())
            {
                Logger.LogWarning("Boot nodes list is empty.");
                return;
            }

            var taskList = NetworkOptions.BootNodes
                .Select(async node =>
                {
                    bool dialed = false;

                    if (!AElfPeerEndpointHelper.TryParse(node, out DnsEndPoint endpoint))
                    {
                        Logger.LogWarning($"Could not parse endpoint {node}.");
                        return;
                    }

                    try
                    {
                        dialed = await _connectionService.ConnectAsync(endpoint);
                    }
                    catch (Exception e)
                    {
                        Logger.LogWarning(e, $"Connect peer failed {node}.");
                    }

                    if (!dialed)
                        await _connectionService.SchedulePeerReconnection(endpoint);

                }).ToList();
            
            await Task.WhenAll(taskList.ToArray<Task>());
        }

19 View Source File : TransactionApiClientTestFixture.cs
License : Apache License 2.0
Project Creator : Actify-Inc

public override async Task InitializeAsync()
        {
            await base.InitializeAsync();

            string dbName = nameof(TransactionApiClientTest);

            await CreateDatabase(dbName);

            ArangoDBClient = GetArangoDBClient(dbName);

            await Task.WhenAll(
                ArangoDBClient.Collection.PostCollectionAsync(new PostCollectionBody
                {
                    Name = TestCollection1
                }),
                ArangoDBClient.Collection.PostCollectionAsync(new PostCollectionBody
                {
                    Name = TestCollection2
                }));
        }

19 View Source File : CustomBatchFixAllProvider.cs
License : Apache License 2.0
Project Creator : agoda-com

public async virtual Task AddDoreplacedentFixesAsync(Doreplacedent doreplacedent, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction> addFix, FixAllContext fixAllContext)
        {
            Debug.replacedert(!diagnostics.IsDefault, "!diagnostics.IsDefault");
            var cancellationToken = fixAllContext.CancellationToken;
            var fixerTasks = new Task[diagnostics.Length];
            var fixes = new List<CodeAction>[diagnostics.Length];

            for (var i = 0; i < diagnostics.Length; i++)
            {
                var currentFixIndex = i;
                cancellationToken.ThrowIfCancellationRequested();
                var diagnostic = diagnostics[i];
                fixerTasks[i] = Task.Run(async () =>
                {
                    var localFixes = new List<CodeAction>();
                    var context = new CodeFixContext(
                        doreplacedent,
                        diagnostic,
                        (a, d) =>
                        {
                            // TODO: Can we share code between similar lambdas that we preplaced to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs?
                            // Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from.
                            lock (localFixes)
                            {
                                localFixes.Add(a);
                            }
                        },
                        cancellationToken);

                    // TODO: Wrap call to ComputeFixesAsync() below in IExtensionManager.PerformFunctionAsync() so that
                    // a buggy extension that throws can't bring down the host?
                    var task = fixAllContext.CodeFixProvider.RegisterCodeFixesAsync(context) ?? SpecializedTasks.CompletedTask;
                    await task.ConfigureAwait(false);

                    cancellationToken.ThrowIfCancellationRequested();
                    localFixes.RemoveAll(action => action.EquivalenceKey != fixAllContext.CodeActionEquivalenceKey);
                    fixes[currentFixIndex] = localFixes;
                });
            }

            await Task.WhenAll(fixerTasks).ConfigureAwait(false);
            foreach (var fix in fixes)
            {
                if (fix == null)
                {
                    continue;
                }

                foreach (var action in fix)
                {
                    addFix(action);
                }
            }
        }

19 View Source File : NetworkingTests.cs
License : MIT License
Project Creator : abdullin

[Test]
        public void ParallelConnectionsToOneMachine() {
            var run = NewTestRuntime();
            run.Connect("local", "api", 
                NetworkProfile.LogAll,
                NetworkProfile.ReverseLatency);


            async Task Connect(IEnv env) {
                using (var c = await env.Connect("api:443")) {
                    await c.Write("Hello");
                    await c.Read(5.Sec());
                }
            };
            
            int connections = 0;

            async Task Handle(IConn c) {
                using (c) {
                    connections++;
                    await c.Read(5.Sec());
                    await c.Write("World");
                }
            }

            
            
            run.AddScript("local", async e => {
                await Task.WhenAll(Connect(e), Connect(e));
                e.Halt("DONE");
            });
            run.AddScript("api", async e => {
                using (var s = await e.Bind(443)) {
                    while (!e.Token.IsCancellationRequested) {
                        Handle(await s.Accept());
                    }
                }
            });
            
            run.Run();
            
            replacedert.AreEqual(2, connections);
        }

19 View Source File : CustomBatchFixAllProvider.cs
License : Apache License 2.0
Project Creator : agoda-com

public virtual async Task<Solution> TryMergeFixesAsync(Solution oldSolution, IEnumerable<CodeAction> codeActions, CancellationToken cancellationToken)
        {
            var changedDoreplacedentsMap = new Dictionary<DoreplacedentId, Doreplacedent>();
            Dictionary<DoreplacedentId, List<Doreplacedent>> doreplacedentsToMergeMap = null;

            foreach (var codeAction in codeActions)
            {
                cancellationToken.ThrowIfCancellationRequested();

                // TODO: Parallelize GetChangedSolutionInternalAsync for codeActions
                var operations = await codeAction.GetPreviewOperationsAsync(cancellationToken).ConfigureAwait(false);
                ApplyChangesOperation singleApplyChangesOperation = null;
                foreach (var operation in operations)
                {
                    var applyChangesOperation = operation as ApplyChangesOperation;
                    if (applyChangesOperation == null)
                    {
                        continue;
                    }

                    if (singleApplyChangesOperation != null)
                    {
                        // Already had an ApplyChangesOperation; only one is supported.
                        singleApplyChangesOperation = null;
                        break;
                    }

                    singleApplyChangesOperation = applyChangesOperation;
                }

                if (singleApplyChangesOperation == null)
                {
                    continue;
                }

                var changedSolution = singleApplyChangesOperation.ChangedSolution;
                var solutionChanges = changedSolution.GetChanges(oldSolution);

                // TODO: Handle added/removed doreplacedents
                // TODO: Handle changed/added/removed additional doreplacedents
                var doreplacedentIdsWithChanges = solutionChanges
                    .GetProjectChanges()
                    .SelectMany(p => p.GetChangedDoreplacedents());

                foreach (var doreplacedentId in doreplacedentIdsWithChanges)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    var doreplacedent = changedSolution.GetDoreplacedent(doreplacedentId);

                    Doreplacedent existingDoreplacedent;
                    if (changedDoreplacedentsMap.TryGetValue(doreplacedentId, out existingDoreplacedent))
                    {
                        if (existingDoreplacedent != null)
                        {
                            changedDoreplacedentsMap[doreplacedentId] = null;
                            var doreplacedentsToMerge = new List<Doreplacedent>();
                            doreplacedentsToMerge.Add(existingDoreplacedent);
                            doreplacedentsToMerge.Add(doreplacedent);
                            doreplacedentsToMergeMap = doreplacedentsToMergeMap ?? new Dictionary<DoreplacedentId, List<Doreplacedent>>();
                            doreplacedentsToMergeMap[doreplacedentId] = doreplacedentsToMerge;
                        }
                        else
                        {
                            doreplacedentsToMergeMap[doreplacedentId].Add(doreplacedent);
                        }
                    }
                    else
                    {
                        changedDoreplacedentsMap[doreplacedentId] = doreplacedent;
                    }
                }
            }

            var currentSolution = oldSolution;
            foreach (var kvp in changedDoreplacedentsMap)
            {
                cancellationToken.ThrowIfCancellationRequested();
                var doreplacedent = kvp.Value;
                if (doreplacedent != null)
                {
                    var doreplacedentText = await doreplacedent.GetTextAsync(cancellationToken).ConfigureAwait(false);
                    currentSolution = currentSolution.WithDoreplacedentText(kvp.Key, doreplacedentText);
                }
            }

            if (doreplacedentsToMergeMap != null)
            {
                var mergedDoreplacedents = new ConcurrentDictionary<DoreplacedentId, SourceText>();
                var doreplacedentsToMergeArray = doreplacedentsToMergeMap.ToImmutableArray();
                var mergeTasks = new Task[doreplacedentsToMergeArray.Length];
                for (var i = 0; i < doreplacedentsToMergeArray.Length; i++)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    var kvp = doreplacedentsToMergeArray[i];
                    var doreplacedentId = kvp.Key;
                    var doreplacedentsToMerge = kvp.Value;
                    var oldDoreplacedent = oldSolution.GetDoreplacedent(doreplacedentId);

                    mergeTasks[i] = Task.Run(async () =>
                    {
                        var appliedChanges = (await doreplacedentsToMerge[0].GetTextChangesAsync(oldDoreplacedent, cancellationToken).ConfigureAwait(false)).ToList();

                        foreach (var doreplacedent in doreplacedentsToMerge.Skip(1))
                        {
                            cancellationToken.ThrowIfCancellationRequested();
                            appliedChanges = await TryAddDoreplacedentMergeChangesAsync(
                                oldDoreplacedent,
                                doreplacedent,
                                appliedChanges,
                                cancellationToken).ConfigureAwait(false);
                        }

                        var oldText = await oldDoreplacedent.GetTextAsync(cancellationToken).ConfigureAwait(false);
                        var newText = oldText.WithChanges(appliedChanges);
                        mergedDoreplacedents.TryAdd(doreplacedentId, newText);
                    });
                }

                await Task.WhenAll(mergeTasks).ConfigureAwait(false);

                foreach (var kvp in mergedDoreplacedents)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    currentSolution = currentSolution.WithDoreplacedentText(kvp.Key, kvp.Value);
                }
            }

            return currentSolution;
        }

19 View Source File : DocumentApiClientTest.cs
License : Apache License 2.0
Project Creator : Actify-Inc

[Fact]
        public async Task DeleteDoreplacedents_ShouldNotThrowButReportFailure_WhenSomeDoreplacedentSelectorsAreInvalid()
        {
            var docTasks = new[] {
                new Dictionary<string, object> { ["Message"] = "first" },
                new Dictionary<string, object> { ["Message"] = "second" }
            }
            .Select(item => _docClient.PostDoreplacedentAsync(_testCollection, item))
            .ToList();

            PostDoreplacedentResponse<Dictionary<string, object>>[] docs =
                await Task.WhenAll(docTasks);

            replacedert.Collection(docs,
                (item) => replacedert.NotNull(item._id),
                (item) => replacedert.NotNull(item._id));

            var ids = docs.Select(d => d._id).ToList();
            ids[1] = "nonsense";

            var response = await _docClient.DeleteDoreplacedentsAsync(_testCollection, ids);
            replacedert.Collection(response,
                // First result succeeds
                (item) => replacedert.NotNull(item._id),
                // Second result fails with NOT_FOUND error
                (item) =>
                {
                    replacedert.Null(item._id);
                    replacedert.True(item.Error);
                    replacedert.Equal(NOT_FOUND_NUM, item.ErrorNum);
                });

            // Should get "not found" for deleted docs
            replacedert.Collection(docs,
                async (item) =>
                {
                    var ex = await replacedert.ThrowsAsync<ApiErrorException>(async () =>
                        await _docClient.GetDoreplacedentAsync<object>(item._id));

                    replacedert.Equal(NOT_FOUND_NUM, ex.ApiError.ErrorNum); // doreplacedent not found)
                },
                async (item) =>
                {
                    var doc = await _docClient.GetDoreplacedentAsync<MyTestClreplaced>(item._id);

                    replacedert.Equal("second", doc.Message); // doreplacedent is found, it was not deleted
                });
        }

19 View Source File : UserOnlyStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public async override Task RemoveClaimsAsync(TUser user, IEnumerable<Claim> claims, CancellationToken cancellationToken = default)
        {
            ThrowIfDisposed();
            replacedertNotNull(user, nameof(user));
            replacedertNotNull(claims, nameof(claims));

            Dictionary<string, TUserClaim> data;
            try
            {
                var response = await _client.GetAsync<Dictionary<string, TUserClaim>>(GetFirebasePath(UserClaimsTableName), cancellationToken, false, $"orderBy=\"UserId\"&equalTo=\"{user.Id}\"")
                    .ConfigureAwait(false);

                data = response.Data;
            }
            catch (FirebaseException e)
                when (e.FirebaseError != null && e.FirebaseError.Error.StartsWith("Index"))
            {
                await SetIndex(UserClaimsTableName, new UserClaimIndex(), cancellationToken)
                    .ConfigureAwait(false);

                var response = await _client.GetAsync<Dictionary<string, TUserClaim>>(GetFirebasePath(UserClaimsTableName), cancellationToken, queryString: $"orderBy=\"UserId\"&equalTo=\"{user.Id}\"")
                    .ConfigureAwait(false);

                data = response.Data;
            }

            if (data != null)
            {
                var taskList = new List<Task>(claims.Count());
                foreach (var claim in claims)
                {
                    var match = data.SingleOrDefault(kv => kv.Value.ClaimType == claim.Type && kv.Value.ClaimValue == claim.Value);
                    if (match.Key != null)
                    {
                        taskList.Add(_client.DeleteAsync(GetFirebasePath(UserClaimsTableName, match.Key), cancellationToken));
                    }
                }

                await Task.WhenAll(taskList.ToArray())
                    .ConfigureAwait(false);
            }
        }

19 View Source File : RedisDatabase.cs
License : MIT License
Project Creator : 17MKH

public async Task DeleteByPrefix(string prefix)
    {
        var pageSize = 1000;
        var pageOffset = 0;
        var hasEnd = false;
        while (!hasEnd)
        {
            var keys = GetKeysByPrefix(prefix, pageSize, pageOffset);
            if (keys == null || !keys.Any())
            {
                hasEnd = true;
            }
            else
            {
                try
                {
                    await _db.KeyDeleteAsync(keys.ToArray());
                }
                catch (RedisCommandException ex)
                {
                    if (ex.Message.StartsWith("Multi-key operations must involve a single slot;"))
                    {
                        await Task.WhenAll(keys.Select(m => _db.KeyDeleteAsync(m)));
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }
        }
    }

19 View Source File : RoleStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public virtual async Task AddClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default)
        {
            ThrowIfDisposed();
            replacedertNotNull(role, nameof(role));
            replacedertNotNull(claim, nameof(claim));

            var roleClaims = await GetRoleClaimsAsync(role).ConfigureAwait(false);

            roleClaims.Add(CreateRoleClaim(role, claim));

            var roleId = ConvertIdToString(role.Id);

            await Task.WhenAll(_db.HashSetAsync(RoleClaimsRedisKey, roleId, JsonConvert.SerializeObject(roleClaims)),
                _db.HashSetAsync(RoleClaimsKeyPrefix + claim.Type, roleId, claim.Value))
                .ConfigureAwait(false);
        }

19 View Source File : DacMissingForeignKeyFix.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public async override Task RegisterCodeFixesAsync(CodeFixContext context)
		{
			context.CancellationToken.ThrowIfCancellationRequested();

			var rootTask = context.Doreplacedent.GetSyntaxRootAsync(context.CancellationToken);
			var semanticModelTask = context.Doreplacedent.GetSemanticModelAsync(context.CancellationToken);

			await Task.WhenAll(rootTask, semanticModelTask).ConfigureAwait(false);

			SyntaxNode root = rootTask.Result;
			SemanticModel semanticModel = semanticModelTask.Result;

			if (!(root?.FindNode(context.Span) is ClreplacedDeclarationSyntax dacNode))
				return;

			INamedTypeSymbol dacTypeSymbol = semanticModel.GetDeclaredSymbol(dacNode, context.CancellationToken);

			if (dacTypeSymbol == null || dacTypeSymbol.MemberNames.Contains(TypeNames.ReferentialIntegrity.ForeignKeyClreplacedName))
				return;

			var pxContext = new PXContext(semanticModel.Compilation, codereplacedysisSettings: null);

			if (pxContext.ReferentialIntegritySymbols.CompositeKey2 == null)
				return;

			var codeActionreplacedle = nameof(Resources.PX1034Fix).GetLocalized().ToString();
			var codeAction = CodeAction.Create(codeActionreplacedle,
											   cancellation => AddForeignKeyDeclarationTemplateToDacAsync(context.Doreplacedent, root, semanticModel, pxContext,
																										  dacNode, dacTypeSymbol, cancellation),
											   equivalenceKey: codeActionreplacedle);

			context.RegisterCodeFix(codeAction, context.Diagnostics);
		}

19 View Source File : WorkFlowManager.cs
License : Apache License 2.0
Project Creator : AbpApp

private async Task<ICollection<WorkflowDefinitionVersion>> LoadWorkflowDefinitionsAsync(CancellationToken cancellationToken)
        {
            using var scope = serviceProvider.CreateScope();
            var providers = scope.ServiceProvider.GetServices<IWorkflowProvider>();
            var tasks = await Task.WhenAll(providers.Select(x => x.GetWorkflowDefinitionsAsync(cancellationToken)));
            return tasks.SelectMany(x => x).ToList();
        }

19 View Source File : IntegrationTest.cs
License : MIT License
Project Creator : 0x1000000

[Test]
        public async Task Test_OldWay()
        {
            var sw = Stopwatch.StartNew();

            Task<int> get1 = Get1();
            Task<int> get2 = Get2();
            Task<string> get3Str = Get3Str();
            Task<int> get4 = Get4();

            await Task.WhenAll(get1, get2, get3Str, get4);

            var result = get1.Result + get2.Result + int.Parse(get3Str.Result) + get4.Result;


            sw.Stop();

            replacedert.AreEqual(9, result);
            replacedert.GreaterOrEqual(sw.ElapsedMilliseconds, TimeSlotMs);
            replacedert.Less(sw.ElapsedMilliseconds, TimeSlotMs + LagMs);
        }

19 View Source File : ResourceTokenBrokerService.cs
License : MIT License
Project Creator : 1iveowl

private async Task<IEnumerable<(User user, IPermissionScope permissionScope)>> GetOrCreatePermissionUsers(string userId, CancellationToken ct)
        {
            // Create a user creation task for each of the permission type - i.e. a user for read-only, a user for read-write etc.
            var permissionUserTasks = KnownPermissionScopes
                .Select(permissionScope => GetOrCreateUser(userId, permissionScope, ct));

            // Run user creations in parallel. 
            return await Task.WhenAll(permissionUserTasks);
        }

public async Task<TradeUnsubscribeAck> Unsubscribe(string tickerSymbol, TradeEventType[] events, IActorRef subscriber)
        {
            var tasks = ToTopics(tickerSymbol, events).Select(x =>
                _mediator.Ask<UnsubscribeAck>(new Unsubscribe(x, subscriber), TimeSpan.FromSeconds(3)));

            await Task.WhenAll(tasks).ConfigureAwait(false);

            return new TradeUnsubscribeAck(tickerSymbol, events);
        }

19 View Source File : TickerManager.cs
License : MIT License
Project Creator : acid-chicken

public static async Task WorkAsync(CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                await Task.WhenAll
                (
                    RequestLogAsync(new LogMessage(LogSeverity.Verbose, "TickerManager", "Calling tasks.")),
                    SetGameAsTickerAsync(),
                    Task.Delay(60000)
                ).ConfigureAwait(false);
            }
        }

19 View Source File : TargetCollection.cs
License : Apache License 2.0
Project Creator : adamralph

private async Task RunAsync(
            Target target,
            List<Target> explicitTargets,
            bool dryRun,
            bool parallel,
            bool skipDependencies,
            Func<Exception, bool> messageOnly,
            Output output,
            Dictionary<Target, Task> runningTargets,
            SemapreplacedSlim sync,
            Queue<Target> dependencyPath)
        {
            if (output.Verbose)
            {
                // can switch to ImmutableQueue after moving to .NET 5+
                dependencyPath = new Queue<Target>(dependencyPath);
                dependencyPath.Enqueue(target);
            }

            bool targetWasAlreadyStarted;
            Task runningTarget;

            // cannot use WaitAsync() as it is not reentrant
#pragma warning disable CA1849 // Call async methods when in an async method
            sync.Wait();
#pragma warning restore CA1849 // Call async methods when in an async method

            try
            {
                targetWasAlreadyStarted = runningTargets.TryGetValue(target, out runningTarget);
            }
            finally
            {
                _ = sync.Release();
            }

            if (targetWasAlreadyStarted)
            {
                if (runningTarget.IsAwaitable())
                {
                    await output.Awaiting(target, dependencyPath).Tax();
                    await runningTarget.Tax();
                }

                return;
            }

            await output.WalkingDependencies(target, dependencyPath).Tax();

            if (parallel)
            {
                var tasks = target.Dependencies.Select(RunDependencyAsync);
                await Task.WhenAll(tasks).Tax();
            }
            else
            {
                foreach (var dependency in target.Dependencies)
                {
                    await RunDependencyAsync(dependency).Tax();
                }
            }

            async Task RunDependencyAsync(string dependency)
            {
                if (!this.Contains(dependency))
                {
                    await output.IgnoringNonExistentDependency(target, dependency, dependencyPath).Tax();
                }
                else
                {
                    await this.RunAsync(this[dependency], explicitTargets, dryRun, false, skipDependencies, messageOnly, output, runningTargets, sync, dependencyPath).Tax();
                }
            }

            if (!skipDependencies || explicitTargets.Contains(target))
            {
                // cannot use WaitAsync() as it is not reentrant
#pragma warning disable CA1849 // Call async methods when in an async method
                sync.Wait();
#pragma warning restore CA1849 // Call async methods when in an async method

                try
                {
                    targetWasAlreadyStarted = runningTargets.TryGetValue(target, out runningTarget);

                    if (!targetWasAlreadyStarted)
                    {
                        runningTarget = target.RunAsync(dryRun, parallel, output, messageOnly, dependencyPath);
                        runningTargets.Add(target, runningTarget);
                    }
                }
                finally
                {
                    _ = sync.Release();
                }

                if (!targetWasAlreadyStarted || runningTarget.IsAwaitable())
                {
                    await output.Awaiting(target, dependencyPath).Tax();
                    await runningTarget.Tax();
                }
            }
        }

See More Examples