System.Threading.Tasks.Task.WhenAll(System.Collections.Generic.IEnumerable)

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

1664 Examples 7

19 Source : MenuService.cs
with MIT License
from 17MKH

[Transaction]
    public async Task<IResultModel> UpdateSort(IList<MenuEnreplacedy> menus)
    {
        if (!menus.Any())
            return ResultModel.Success();

        var tasks = new List<Task>();
        foreach (var menu in menus)
        {
            var task = _repository.Find(m => m.Id == menu.Id).ToUpdate(m => new MenuEnreplacedy
            {
                ParentId = menu.ParentId,
                Sort = menu.Sort
            });
            tasks.Add(task);
        }

        await Task.WhenAll(tasks);

        return ResultModel.Success();
    }

19 Source : RoleService.cs
with MIT License
from 17MKH

[Transaction]
    public async Task<IResultModel> UpdateBindMenus(RoleBindMenusUpdateDto dto)
    {
        var role = await _repository.Get(dto.RoleId);
        if (role == null)
            return ResultModel.NotExists;

        //删除当前角色已绑定的菜单数据
        await _roleMenuRepository.Find(m => m.MenuGroupId == role.MenuGroupId && m.RoleId == role.Id).ToDelete();

        //删除当前角色已绑定的按钮数据
        await _roleButtonRepository.Find(m => m.MenuGroupId == role.MenuGroupId && m.RoleId == role.Id).ToDelete();

        //删除当前角色已绑定的权限数据
        await _rolePermissionRepository.Find(m => m.MenuGroupId == role.MenuGroupId && m.RoleId == role.Id).ToDelete();

        //添加绑定菜单数据
        if (dto.Menus.NotNullAndEmpty())
        {
            foreach (var dtoMenu in dto.Menus)
            {
                await _roleMenuRepository.Add(new RoleMenuEnreplacedy
                {
                    MenuGroupId = role.MenuGroupId,
                    RoleId = role.Id,
                    MenuId = dtoMenu.MenuId,
                    MenuType = dtoMenu.MenuType
                });

                var tasks = new List<Task>();

                //添加绑定按钮数据
                if (dtoMenu.Buttons.NotNullAndEmpty())
                {
                    foreach (var dtoButton in dtoMenu.Buttons)
                    {
                        tasks.Add(_roleButtonRepository.Add(new RoleButtonEnreplacedy
                        {
                            MenuGroupId = role.MenuGroupId,
                            MenuId = dtoMenu.MenuId,
                            RoleId = role.Id,
                            ButtonCode = dtoButton.ToLower()
                        }));
                    }
                }

                //添加绑定权限数据
                if (dtoMenu.Permissions.NotNullAndEmpty())
                {
                    foreach (var dtoPermission in dtoMenu.Permissions)
                    {
                        tasks.Add(_rolePermissionRepository.Add(new RolePermissionEnreplacedy
                        {
                            MenuGroupId = role.MenuGroupId,
                            RoleId = role.Id,
                            MenuId = dtoMenu.MenuId,
                            PermissionCode = dtoPermission.ToLower()
                        }));
                    }
                }

                await Task.WhenAll(tasks);
            }
        }

        //清除关联账户的权限缓存
        var accountIds = await _accountRepository.Find(m => m.RoleId == dto.RoleId).Select(m => m.Id).ToList<Guid>();
        if (accountIds.Any())
        {
            var tasks = new List<Task>();
            foreach (var accountId in accountIds)
            {
                tasks.Add(_cacheHandler.Remove(_cacheKeys.AccountPermissions(accountId, 0)));
            }

            await Task.WhenAll(tasks);
        }

        return ResultModel.Success();
    }

19 Source : ResourceTokenBrokerService.cs
with MIT License
from 1iveowl

private async Task<IResourcePermissionResponse> GetOrCreatePermissions(
            IEnumerable<(User user, IPermissionScope permissionScope)> usersWithPermisssionScope,
            string userId,
            CancellationToken ct)
        {
            _parreplacedionKeyHeader = await GetPartionKeyHeader(ct);

            var getOrCreateUserPermissionsTask = usersWithPermisssionScope
                .Select(tuple => GetOrCreateUserPermission(tuple.user, userId, tuple.permissionScope, ct));

            var permissions = await Task.WhenAll(getOrCreateUserPermissionsTask);
            
            return new ResourcePermissionResponse(permissions, userId, _endpointUrl, _databaseId, _collectionId, _parreplacedionKeyHeader);
        }

19 Source : DigitalAnalyzerExampleViewModel.cs
with MIT License
from ABTSoftware

private async Task GenerateData(List<byte[]> digitalChannels, List<float[]> replacedogChannels)
        {
            var digitalChannelsCount = digitalChannels.Count;
            var replacedogChannelsCount = replacedogChannels.Count;

            var totalChannelCount = digitalChannelsCount + replacedogChannelsCount;
            var channelList = new List<ChannelViewModel>(totalChannelCount);
            var channelIndex = ChannelViewModels.Count;

            await Task.Run(async () =>
            {
                var xStart = 0d;
                var xStep = 1d;

                var digital = new List<Task<ChannelViewModel>>(digitalChannelsCount);
                var replacedog = new List<Task<ChannelViewModel>>(replacedogChannelsCount);

                foreach (var channel in digitalChannels)
                {
                    var id = channelIndex++;
                    digital.Add(Task.Run(() => ChannelGenerationHelper.Instance.GenerateDigitalChannel(xStart, xStep, channel, id)));
                }
                foreach (var channel in replacedogChannels)
                {
                    var id = channelIndex++;
                    replacedog.Add(Task.Run(() => ChannelGenerationHelper.Instance.GeneratereplacedogChannel(xStart, xStep, channel, id)));
                }

                await Task.WhenAll(digital.Union(replacedog));

                foreach (var p in digital.Union(replacedog))
                {
                    channelList.Add(p.Result);
                }
            });

            channelList.ForEach(ch => ChannelViewModels.Add(ch));
        }

19 Source : DigitalAnalyzerExampleViewModel.cs
with MIT License
from ABTSoftware

private async Task GenerateData(List<byte[]> digitalChannels)
        {
            var digitalChannelsCount = digitalChannels.Count;

            var channelList = new List<ChannelViewModel>(digitalChannelsCount);
            var channelIndex = ChannelViewModels.Count;

            await Task.Run(async () =>
            {
                var xStart = 0d;
                var xStep = 1d;

                var channels = new List<Task<ChannelViewModel>>(digitalChannelsCount);

                foreach (var channel in digitalChannels)
                {
                    var id = channelIndex++;
                    channels.Add(Task.Run(() => ChannelGenerationHelper.Instance.GenerateDigitalChannel(xStart, xStep, channel, id)));
                }

                await Task.WhenAll(channels);

                foreach (var p in channels)
                {
                    channelList.Add(p.Result);
                }
            });

            channelList.ForEach(ch => ChannelViewModels.Add(ch));
        }

19 Source : InternetCheck.cs
with MIT License
from actions

public async Task<bool> RunCheck(string url, string pat)
        {
            await File.AppendAllLinesAsync(_logFile, HostContext.WarnLog());
            await File.AppendAllLinesAsync(_logFile, HostContext.CheckProxy());

            var checkTasks = new List<Task<CheckResult>>();
            checkTasks.Add(CheckUtil.CheckDns("https://api.github.com"));
            checkTasks.Add(CheckUtil.CheckPing("https://api.github.com"));

            // We don't need to preplaced a PAT since it might be a token for GHES.
            checkTasks.Add(HostContext.CheckHttpsGetRequests("https://api.github.com", pat: null, expectedHeader: "X-GitHub-Request-Id"));

            var result = true;
            while (checkTasks.Count > 0)
            {
                var finishedCheckTask = await Task.WhenAny<CheckResult>(checkTasks);
                var finishedCheck = await finishedCheckTask;
                result = result && finishedCheck.Preplaced;
                await File.AppendAllLinesAsync(_logFile, finishedCheck.Logs);
                checkTasks.Remove(finishedCheckTask);
            }

            await Task.WhenAll(checkTasks);
            return result;
        }

19 Source : ActionsCheck.cs
with MIT License
from actions

public async Task<bool> RunCheck(string url, string pat)
        {
            await File.AppendAllLinesAsync(_logFile, HostContext.WarnLog());
            await File.AppendAllLinesAsync(_logFile, HostContext.CheckProxy());

            var checkTasks = new List<Task<CheckResult>>();
            string githubApiUrl = null;
            string actionsTokenServiceUrl = null;
            string actionsPipelinesServiceUrl = null;
            var urlBuilder = new UriBuilder(url);
            if (UrlUtil.IsHostedServer(urlBuilder))
            {
                urlBuilder.Host = $"api.{urlBuilder.Host}";
                urlBuilder.Path = "";
                githubApiUrl = urlBuilder.Uri.AbsoluteUri;
                actionsTokenServiceUrl = "https://vstoken.actions.githubusercontent.com/_apis/health";
                actionsPipelinesServiceUrl = "https://pipelines.actions.githubusercontent.com/_apis/health";
            }
            else
            {
                urlBuilder.Path = "api/v3";
                githubApiUrl = urlBuilder.Uri.AbsoluteUri;
                urlBuilder.Path = "_services/vstoken/_apis/health";
                actionsTokenServiceUrl = urlBuilder.Uri.AbsoluteUri;
                urlBuilder.Path = "_services/pipelines/_apis/health";
                actionsPipelinesServiceUrl = urlBuilder.Uri.AbsoluteUri;
            }

            // check github api
            checkTasks.Add(CheckUtil.CheckDns(githubApiUrl));
            checkTasks.Add(CheckUtil.CheckPing(githubApiUrl));
            checkTasks.Add(HostContext.CheckHttpsGetRequests(githubApiUrl, pat, expectedHeader: "X-GitHub-Request-Id"));

            // check actions token service
            checkTasks.Add(CheckUtil.CheckDns(actionsTokenServiceUrl));
            checkTasks.Add(CheckUtil.CheckPing(actionsTokenServiceUrl));
            checkTasks.Add(HostContext.CheckHttpsGetRequests(actionsTokenServiceUrl, pat, expectedHeader: "x-vss-e2eid"));

            // check actions pipelines service
            checkTasks.Add(CheckUtil.CheckDns(actionsPipelinesServiceUrl));
            checkTasks.Add(CheckUtil.CheckPing(actionsPipelinesServiceUrl));
            checkTasks.Add(HostContext.CheckHttpsGetRequests(actionsPipelinesServiceUrl, pat, expectedHeader: "x-vss-e2eid"));

            // check HTTP POST to actions pipelines service
            checkTasks.Add(HostContext.CheckHttpsPostRequests(actionsPipelinesServiceUrl, pat, expectedHeader: "x-vss-e2eid"));

            var result = true;
            while (checkTasks.Count > 0)
            {
                var finishedCheckTask = await Task.WhenAny<CheckResult>(checkTasks);
                var finishedCheck = await finishedCheckTask;
                result = result && finishedCheck.Preplaced;
                await File.AppendAllLinesAsync(_logFile, finishedCheck.Logs);
                checkTasks.Remove(finishedCheckTask);
            }

            await Task.WhenAll(checkTasks);
            return result;
        }

19 Source : FileContainerServer.cs
with MIT License
from actions

private async Task<DownloadResult> ParallelDownloadAsync(RunnerActionPluginExecutionContext context, IReadOnlyList<DownloadInfo> files, int concurrentDownloads, CancellationToken token)
        {
            // return files that fail to download
            var downloadResult = new DownloadResult();

            // nothing needs to download
            if (files.Count == 0)
            {
                return downloadResult;
            }

            // ensure the file download queue is empty.
            if (!_fileDownloadQueue.IsEmpty)
            {
                throw new ArgumentOutOfRangeException(nameof(_fileDownloadQueue));
            }

            // enqueue file into download queue.
            foreach (var file in files)
            {
                _fileDownloadQueue.Enqueue(file);
            }

            // Start download monitor task.
            _downloadFilesProcessed = 0;
            _downloadFinished = new TaskCompletionSource<int>();
            Task downloadMonitor = DownloadReportingAsync(context, files.Count(), token);

            // Start parallel download tasks.
            List<Task<DownloadResult>> parallelDownloadingTasks = new List<Task<DownloadResult>>();
            for (int downloader = 0; downloader < concurrentDownloads; downloader++)
            {
                parallelDownloadingTasks.Add(DownloadAsync(context, downloader, token));
            }

            // Wait for parallel download finish.
            await Task.WhenAll(parallelDownloadingTasks);
            foreach (var downloadTask in parallelDownloadingTasks)
            {
                // record all failed files.
                downloadResult.AddDownloadResult(await downloadTask);
            }

            // Stop monitor task;
            _downloadFinished.TrySetResult(0);
            await downloadMonitor;

            return downloadResult;
        }

19 Source : FileContainerServer.cs
with MIT License
from actions

private async Task<UploadResult> ParallelUploadAsync(RunnerActionPluginExecutionContext context, IReadOnlyList<string> files, int concurrentUploads, CancellationToken token)
        {
            // return files that fail to upload and total artifact size
            var uploadResult = new UploadResult();

            // nothing needs to upload
            if (files.Count == 0)
            {
                return uploadResult;
            }

            // ensure the file upload queue is empty.
            if (!_fileUploadQueue.IsEmpty)
            {
                throw new ArgumentOutOfRangeException(nameof(_fileUploadQueue));
            }

            // enqueue file into upload queue.
            foreach (var file in files)
            {
                _fileUploadQueue.Enqueue(file);
            }

            // Start upload monitor task.
            _uploadFilesProcessed = 0;
            _uploadFinished = new TaskCompletionSource<int>();
            _fileUploadTraceLog.Clear();
            _fileUploadProgressLog.Clear();
            Task uploadMonitor = UploadReportingAsync(context, files.Count(), _uploadCancellationTokenSource.Token);

            // Start parallel upload tasks.
            List<Task<UploadResult>> parallelUploadingTasks = new List<Task<UploadResult>>();
            for (int uploader = 0; uploader < concurrentUploads; uploader++)
            {
                parallelUploadingTasks.Add(UploadAsync(context, uploader, _uploadCancellationTokenSource.Token));
            }

            // Wait for parallel upload finish.
            await Task.WhenAll(parallelUploadingTasks);
            foreach (var uploadTask in parallelUploadingTasks)
            {
                // record all failed files.
                uploadResult.AddUploadResult(await uploadTask);
            }

            // Stop monitor task;
            _uploadFinished.TrySetResult(0);
            await uploadMonitor;

            return uploadResult;
        }

19 Source : BankIdEventTrigger.cs
with MIT License
from ActiveLogin

public async Task TriggerAsync(BankIdEvent bankIdEvent)
        {
            if (bankIdEvent == null)
            {
                throw new ArgumentNullException(nameof(bankIdEvent));
            }

            bankIdEvent.SetContext(_bankIdActiveLoginContext);

            var tasks = new List<Task>();

            foreach (var listener in _listeners)
            {
                tasks.Add(listener.HandleAsync(bankIdEvent));
            }

            await Task.WhenAll(tasks);
        }

19 Source : BankIdResultStoreEventListener.cs
with MIT License
from ActiveLogin

public override async Task HandleCollectCompletedEvent(BankIdCollectCompletedEvent e)
        {
            var tasks = new List<Task>();

            foreach (var bankIdResultStore in _bankIdResultStores)
            {
                tasks.Add(bankIdResultStore.StoreCollectCompletedCompletionData(e.OrderRef, e.CompletionData));
            }

            await Task.WhenAll(tasks);
        }

19 Source : ProjectSet.cs
with MIT License
from adamant

public async Task Build(TaskScheduler taskScheduler, bool verbose)
        {
            _ = verbose; // verbose parameter will be needed in the future
            var taskFactory = new TaskFactory(taskScheduler);
            var projectBuilds = new Dictionary<Project, Task<PackageIL?>>();

            var projectBuildsSource = new TaskCompletionSource<FixedDictionary<Project, Task<PackageIL?>>>();
            var projectBuildsTask = projectBuildsSource.Task;

            // Sort projects to detect cycles and so we can replacedume the tasks already exist
            var sortedProjects = TopologicalSort();
            var compiler = new AdamantCompiler();
            var consoleLock = new object();
            foreach (var project in sortedProjects)
            {
#pragma warning disable CA2008 // Do not create tasks without preplaceding a TaskScheduler (created with task factory built with task scheduler)
                var buildTask = taskFactory.StartNew(() =>
                    Build(compiler, project, projectBuildsTask, consoleLock))
#pragma warning restore CA2008 // Do not create tasks without preplaceding a TaskScheduler
                    .Unwrap(); // Needed because StartNew doesn't work intuitively with Async methods
                if (!projectBuilds.TryAdd(project, buildTask))
                    throw new Exception("Project added to build set twice");
            }
            projectBuildsSource.SetResult(projectBuilds.ToFixedDictionary());

            await Task.WhenAll(projectBuilds.Values).ConfigureAwait(false);
        }

19 Source : ActionTarget`1.cs
with Apache License 2.0
from adamralph

public override async Task RunAsync(bool dryRun, bool parallel, Output output, Func<Exception, bool> messageOnly, IReadOnlyCollection<Target> dependencyPath)
        {
            var inputsList = this.inputs.ToList();

            if (inputsList.Count == 0)
            {
                await output.NoInputs(this, dependencyPath).Tax();
                return;
            }

            await output.BeginGroup(this).Tax();
            await output.Starting(this, dependencyPath).Tax();

            try
            {
                if (parallel)
                {
                    var tasks = inputsList.Select(input => this.RunAsync(input, dryRun, output, messageOnly, dependencyPath)).ToList();

                    await Task.WhenAll(tasks).Tax();
                }
                else
                {
                    foreach (var input in inputsList)
                    {
                        await this.RunAsync(input, dryRun, output, messageOnly, dependencyPath).Tax();
                    }
                }
            }
            catch (Exception)
            {
                await output.Failed(this, dependencyPath).Tax();
                await output.EndGroup().Tax();

                throw;
            }

            await output.Succeeded(this, dependencyPath).Tax();
            await output.EndGroup().Tax();
        }

19 Source : SettingsTest.cs
with MIT License
from adams85

[Fact]
        public async Task ReloadOptionsSettingsMultipleProviders()
        {
            var fileProvider = new MemoryFileProvider();
            var fileAppender = new MemoryFileAppender(fileProvider);

            dynamic settings = new JObject();
            dynamic globalFilters = settings[nameof(LoggerFilterRule.LogLevel)] = new JObject();
            globalFilters[LogFileOptions.DefaultCategoryName] = LogLevel.None.ToString();

            settings[FileLoggerProvider.Alias] = new JObject();
            dynamic fileFilters = settings[FileLoggerProvider.Alias][nameof(LoggerFilterRule.LogLevel)] = new JObject();
            fileFilters[LogFileOptions.DefaultCategoryName] = LogLevel.Warning.ToString();
            dynamic oneFile = new JObject();
            oneFile.Path = "one.log";
            settings[FileLoggerProvider.Alias][nameof(FileLoggerOptions.Files)] = new JArray(oneFile);

            settings[OtherFileLoggerProvider.Alias] = new JObject();
            dynamic otherFileFilters = settings[OtherFileLoggerProvider.Alias][nameof(LoggerFilterRule.LogLevel)] = new JObject();
            otherFileFilters[LogFileOptions.DefaultCategoryName] = LogLevel.Information.ToString();
            dynamic otherFile = new JObject();
            otherFile.Path = "other.log";
            settings[OtherFileLoggerProvider.Alias][nameof(FileLoggerOptions.Files)] = new JArray(otherFile);

            var configJson = ((JObject)settings).ToString();

            fileProvider.CreateFile("config.json", configJson);

            IConfigurationRoot config = new ConfigurationBuilder()
                .AddJsonFile(fileProvider, "config.json", optional: false, reloadOnChange: true)
                .Build();

            var context = new TestFileLoggerContext(default, completionTimeout: Timeout.InfiniteTimeSpan);

            var services = new ServiceCollection();
            services.AddOptions();
            services.AddLogging(lb =>
            {
                lb.AddConfiguration(config);
                lb.AddFile(context, o => o.FileAppender ??= fileAppender);
                lb.AddFile<OtherFileLoggerProvider>(context, o => o.FileAppender ??= fileAppender);
            });

            FileLoggerProvider[] providers;

            using (ServiceProvider sp = services.BuildServiceProvider())
            {
                providers = context.GetProviders(sp).ToArray();
                replacedert.Equal(2, providers.Length);

                var resetTasks = new List<Task>();
                foreach (FileLoggerProvider provider in providers)
                    provider.Reset += (s, e) => resetTasks.Add(e);

                ILoggerFactory loggerFactory = sp.GetRequiredService<ILoggerFactory>();

                ILogger logger = loggerFactory.CreateLogger("X");

                logger.LogInformation("This is an info.");
                logger.LogWarning("This is a warning.");

                fileFilters[LogFileOptions.DefaultCategoryName] = LogLevel.Information.ToString();
                otherFileFilters[LogFileOptions.DefaultCategoryName] = LogLevel.Warning.ToString();
                configJson = ((JObject)settings).ToString();

                replacedert.Equal(0, resetTasks.Count);
                fileProvider.WriteContent("config.json", configJson);

                // reload is triggered twice due to a bug in the framework (https://github.com/aspnet/Logging/issues/874)
                replacedert.Equal(2 * 2, resetTasks.Count);

                // ensuring that reset has been finished and the new settings are effective
                await Task.WhenAll(resetTasks);

                logger.LogInformation("This is another info.");
                logger.LogWarning("This is another warning.");
            }

            replacedert.True(providers.All(provider => provider.Completion.IsCompleted));

            var logFile = (MemoryFileInfo)fileProvider.GetFileInfo((string)oneFile.Path);
            replacedert.True(logFile.Exists && !logFile.IsDirectory);

            var lines = logFile.ReadAllText(out Encoding encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            replacedert.Equal(Encoding.UTF8, encoding);
            replacedert.Equal(new[]
            {
                $"warn: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
                $"      This is a warning.",
                $"info: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
                $"      This is another info.",
                $"warn: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
                $"      This is another warning.",
                ""
            }, lines);

            logFile = (MemoryFileInfo)fileProvider.GetFileInfo((string)otherFile.Path);
            replacedert.True(logFile.Exists && !logFile.IsDirectory);

            lines = logFile.ReadAllText(out encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            replacedert.Equal(Encoding.UTF8, encoding);
            replacedert.Equal(new[]
            {
                $"info: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
                $"      This is an info.",
                $"warn: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
                $"      This is a warning.",
                $"warn: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
                $"      This is another warning.",
                ""
            }, lines);
        }

19 Source : SettingsTest.cs
with MIT License
from adams85

[Fact]
        public async Task ReloadOptionsSettings()
        {
            var configJson =
$@"{{
    ""{FileLoggerProvider.Alias}"": {{
        ""{nameof(FileLoggerOptions.IncludeScopes)}"" : true,
        ""{nameof(FileLoggerOptions.Files)}"": [
        {{
            ""{nameof(LogFileOptions.Path)}"": ""test.log"",
        }}],
        ""{nameof(LoggerFilterRule.LogLevel)}"": {{ 
            ""{LogFileOptions.DefaultCategoryName}"": ""{LogLevel.Trace}"" 
        }}
    }}
}}";

            var fileProvider = new MemoryFileProvider();
            fileProvider.CreateFile("config.json", configJson, Encoding.UTF8);

            var cb = new ConfigurationBuilder();
            cb.AddJsonFile(fileProvider, "config.json", optional: false, reloadOnChange: true);
            IConfigurationRoot config = cb.Build();

            var completeCts = new CancellationTokenSource();
            var context = new TestFileLoggerContext(completeCts.Token, completionTimeout: Timeout.InfiniteTimeSpan);
            context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));

            var services = new ServiceCollection();
            services.AddOptions();
            services.AddLogging(b =>
            {
                b.AddConfiguration(config);
                b.AddFile(context);
            });

            var fileAppender = new MemoryFileAppender(fileProvider);
            services.Configure<FileLoggerOptions>(o => o.FileAppender ??= fileAppender);

            FileLoggerProvider[] providers;

            using (ServiceProvider sp = services.BuildServiceProvider())
            {
                providers = context.GetProviders(sp).ToArray();
                replacedert.Equal(1, providers.Length);

                var resetTasks = new List<Task>();
                foreach (FileLoggerProvider provider in providers)
                    provider.Reset += (s, e) => resetTasks.Add(e);

                ILoggerFactory loggerFactory = sp.GetService<ILoggerFactory>();
                ILogger<SettingsTest> logger1 = loggerFactory.CreateLogger<SettingsTest>();

                using (logger1.BeginScope("SCOPE"))
                {
                    logger1.LogTrace("This is a nice logger.");

                    using (logger1.BeginScope("NESTED SCOPE"))
                    {
                        logger1.LogInformation("This is a smart logger.");

                        // changing switch and scopes inclusion
                        configJson =
$@"{{
    ""{FileLoggerProvider.Alias}"": {{
        ""{nameof(FileLoggerOptions.Files)}"": [
        {{
            ""{nameof(LogFileOptions.Path)}"": ""test.log"",
        }}],
        ""{nameof(LoggerFilterRule.LogLevel)}"": {{ 
            ""{LogFileOptions.DefaultCategoryName}"": ""{LogLevel.Information}"" 
        }}
    }}
}}";

                        replacedert.Equal(0, resetTasks.Count);
                        fileProvider.WriteContent("config.json", configJson);

                        // reload is triggered twice due to a bug in the framework (https://github.com/aspnet/Logging/issues/874)
                        replacedert.Equal(1 * 2, resetTasks.Count);

                        // ensuring that reset has been finished and the new settings are effective
                        await Task.WhenAll(resetTasks);

                        logger1 = loggerFactory.CreateLogger<SettingsTest>();

                        logger1.LogInformation("This one shouldn't include scopes.");
                        logger1.LogTrace("This one shouldn't be included at all.");
                    }
                }

                completeCts.Cancel();

                // ensuring that all entries are processed
                await context.GetCompletion(sp);
                replacedert.True(providers.All(provider => provider.Completion.IsCompleted));
            }

            var logFile = (MemoryFileInfo)fileProvider.GetFileInfo("test.log");
            replacedert.True(logFile.Exists && !logFile.IsDirectory);

            var lines = logFile.ReadAllText(out Encoding encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            replacedert.Equal(Encoding.UTF8, encoding);
            replacedert.Equal(new[]
            {
                $"trce: {typeof(SettingsTest).FullName}[0] @ {context.GetTimestamp().ToLocalTime():o}",
                $"      => SCOPE",
                $"      This is a nice logger.",
                $"info: {typeof(SettingsTest).FullName}[0] @ {context.GetTimestamp().ToLocalTime():o}",
                $"      => SCOPE => NESTED SCOPE",
                $"      This is a smart logger.",
                $"info: {typeof(SettingsTest).FullName}[0] @ {context.GetTimestamp().ToLocalTime():o}",
                $"      This one shouldn't include scopes.",
                ""
            }, lines);
        }

19 Source : EdgeCasesTest.cs
with MIT License
from adams85

[Fact]
        public async Task FailingEntryDontGetStuck()
        {
            var logsDirName = Guid.NewGuid().ToString("D");

            var tempPath = Path.Combine(Path.GetTempPath());
            var logPath = Path.Combine(tempPath, logsDirName);

            if (Directory.Exists(logPath))
                Directory.Delete(logPath, recursive: true);

            var fileProvider = new PhysicalFileProvider(tempPath);

            var options = new FileLoggerOptions
            {
                FileAppender = new PhysicalFileAppender(fileProvider),
                BasePath = logsDirName,
                Files = new[]
                {
                    new LogFileOptions
                    {
                        Path = "default.log",
                    },
                },
            };
            var optionsMonitor = new DelegatedOptionsMonitor<FileLoggerOptions>(_ => options);

            var completeCts = new CancellationTokenSource();
            var completionTimeoutMs = 2000;
            var context = new TestFileLoggerContext(completeCts.Token, TimeSpan.FromMilliseconds(completionTimeoutMs), writeRetryDelay: TimeSpan.FromMilliseconds(250));
            context.SetTimestamp(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc));

            var services = new ServiceCollection();
            services.AddOptions();
            services.AddLogging(b => b.AddFile(context));
            services.AddSingleton<IOptionsMonitor<FileLoggerOptions>>(optionsMonitor);

            string filePath = Path.Combine(logPath, "default.log");

            try
            {
                FileLoggerProvider[] providers;

                using (ServiceProvider sp = services.BuildServiceProvider())
                {
                    providers = context.GetProviders(sp).ToArray();
                    replacedert.Equal(1, providers.Length);

                    var resetTasks = new List<Task>();
                    foreach (FileLoggerProvider provider in providers)
                        provider.Reset += (s, e) => resetTasks.Add(e);

                    ILoggerFactory loggerFactory = sp.GetRequiredService<ILoggerFactory>();
                    ILogger logger = loggerFactory.CreateLogger("X");

                    logger.LogInformation("This should get through.");

                    optionsMonitor.Reload();
                    // ensuring that reset has been finished and the new settings are effective
                    await Task.WhenAll(resetTasks);

                    using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        logger.LogInformation("This shouldn't get through.");

                        Task completion = context.GetCompletion(sp);
                        replacedert.False(completion.IsCompleted);

                        completeCts.Cancel();

                        replacedert.Equal(completion, await Task.WhenAny(completion, Task.Delay(TimeSpan.FromMilliseconds(completionTimeoutMs * 2))));
                        replacedert.Equal(TaskStatus.RanToCompletion, completion.Status);
                    }
                }

                IFileInfo logFile = fileProvider.GetFileInfo($"{logsDirName}/default.log");
                replacedert.True(logFile.Exists && !logFile.IsDirectory);

                var lines = logFile.ReadAllText(out Encoding encoding).Split(new[] { Environment.NewLine }, StringSplitOptions.None);
                replacedert.Equal(Encoding.UTF8, encoding);
                replacedert.Equal(new[]
                {
                    $"info: X[0] @ {context.GetTimestamp().ToLocalTime():o}",
                    $"      This should get through.",
                    ""
                }, lines);
            }
            finally
            {
                Directory.Delete(logPath, recursive: true);
            }
        }

19 Source : JobRescuerHostedService.cs
with MIT License
from AdemCatamak

private async Task BackgroundJob(CancellationToken cancellationToken)
        {
            using IServiceScope scope = _serviceProvider.CreateScope();

            var jobRescuer = scope.ServiceProvider
                                  .GetRequiredService<IJobRescuer>();

            List<RescueOption> rescueOptions = scope.ServiceProvider
                                                    .GetServices<MessageHandlerMetadata>()
                                                    .Select(metaData => metaData.RescueOption)
                                                    .ToList()!;

            List<Task> operationList = new List<Task>();
            foreach (var rescueOption in rescueOptions)
            {
                Task rescueAsync = jobRescuer.RescueAsync(rescueOption, cancellationToken);
                operationList.Add(rescueAsync);
            }

            await Task.WhenAll(operationList);
        }

19 Source : JobRetrierHostedService.cs
with MIT License
from AdemCatamak

private async Task BackgroundJob(CancellationToken cancellationToken)
        {
            using IServiceScope scope = _serviceProvider.CreateScope();

            var jobRetrier = scope.ServiceProvider
                                  .GetRequiredService<IJobRetrier>();

            List<RetryOption> retryOptions = scope.ServiceProvider
                                                  .GetServices<MessageHandlerMetadata>()
                                                  .Where(metaData => metaData.RetryOption != null)
                                                  .Select(metaData => metaData.RetryOption)
                                                  .ToList()!;

            List<Task> operationList = new List<Task>();
            foreach (var retryOption in retryOptions)
            {
                Task retryAsync = jobRetrier.RetryAsync(retryOption, cancellationToken);
                operationList.Add(retryAsync);
            }

            await Task.WhenAll(operationList);
        }

19 Source : IBlockchainService.cs
with MIT License
from AElfProject

public static async Task<List<Block>> GetBlocksInChainBranchAsync(this IBlockchainService blockchainService,
            Chain chain,
            Hash firstHash,
            int count,
            Hash chainBranch)
        {
            var blockHashes = await blockchainService.GetBlockHashesAsync(
                chain, firstHash, count, chainBranch);
            var list = blockHashes
                .Select(async blockHash => await blockchainService.GetBlockByHashAsync(blockHash));

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

19 Source : BlockchainServiceExtensions.cs
with MIT License
from AElfProject

public static async Task<List<Block>> GetBlocksAsync(this IBlockchainService blockchainService,
            IEnumerable<Hash> blockHashes)
        {
            var list = blockHashes
                .Select(async blockHash => await blockchainService.GetBlockByHashAsync(blockHash));

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

19 Source : UserOnlyStore.cs
with Apache License 2.0
from 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));

            var userClaims = await GetUserClaimsAsync(user).ConfigureAwait(false);

            userClaims.AddRange(claims.Select(c => CreateUserClaim(user, c)));

            var userId = ConvertIdToString(user.Id);

            var taskList = new List<Task>(claims.Count() + 1)
            {
                _db.HashSetAsync(UserClaimsRedisKey, userId, JsonConvert.SerializeObject(userClaims))
            };
            foreach (var claim in claims)
            {
                taskList.Add(_db.HashSetAsync(UserClaimsKeyPrefix + claim.Type, userId, claim.Value));
            }

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

19 Source : UserOnlyStore.cs
with Apache License 2.0
from Aguafrommars

public async override Task ReplaceClaimAsync(TUser user, Claim claim, Claim newClaim, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            replacedertNotNull(user, nameof(user));
            replacedertNotNull(claim, nameof(claim));
            replacedertNotNull(newClaim, nameof(newClaim));

            var userId = ConvertIdToString(user.Id);

            var userClaims = await GetUserClaimsAsync(user).ConfigureAwait(false);
            var taskList = new List<Task>(3);
            await Task.WhenAll(taskList).ConfigureAwait(false);
            foreach (var uc in userClaims)
            {
                if (uc.ClaimType == claim.Type && uc.ClaimValue == claim.Value)
                {
                    uc.ClaimType = newClaim.Type;
                    uc.ClaimValue = newClaim.Value;
                    taskList.Add(_db.HashDeleteAsync(UserClaimsKeyPrefix + claim.Type, userId));
                    taskList.Add(_db.HashSetAsync(UserClaimsKeyPrefix + newClaim.Type, userId, newClaim.Value));
                }
            }

            taskList.Add(_db.HashSetAsync(UserClaimsRedisKey, userId, JsonConvert.SerializeObject(userClaims)));
            await Task.WhenAll(taskList).ConfigureAwait(false);
        }

19 Source : UserStore.cs
with Apache License 2.0
from Aguafrommars

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

            var userId = ConvertIdToString(user.Id);

            var userRoles = await GetUserRolesAsync(userId).ConfigureAwait(false);
            var taskList = new List<Task<TRole>>(userRoles.Count);

            foreach(var userRole in userRoles)
            {
                taskList.Add(FindRoleByIdAsync(ConvertIdToString(userRole.RoleId), cancellationToken));
            }

            var result = await Task.WhenAll(taskList)
                .ConfigureAwait(false);

            return result.Where(r => r != null)
                .Select(r => r.Name)
                .ToList();
        }

19 Source : UserStore.cs
with Apache License 2.0
from Aguafrommars

public async override Task<IList<TUser>> GetUsersInRoleAsync(string roleName, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            replacedertNotNullOrEmpty(roleName, nameof(roleName));

            var users = await _db.HashGetAllAsync(UserRolesNameIndexKey + roleName)
                .ConfigureAwait(false);
            var taskList = new List<Task<TUser>>(users.Length);
            foreach(var user in users)
            {
                taskList.Add(FindByIdAsync(user.Name, cancellationToken));
            }

            var results = await Task.WhenAll(taskList)
                .ConfigureAwait(false);

            return results.Where(u => u != null)
                .Select(u => u)
                .ToList();
        }

19 Source : EntityModel.cs
with Apache License 2.0
from Aguafrommars

private async Task HandleMoficationList(Type enreplacedyType, Dictionary<object, ModificationKind> modificationList)
        {
            Logger.LogDebug($"HandleMoficationList for type {enreplacedyType.Name}");
            var addList = GetModifiedEnreplacedies(modificationList, ModificationKind.Add);
            var taskList = new List<Task>(addList.Count());
            foreach (var enreplacedy in addList)
            {
                taskList.Add(AddEnreplacedyAsync(enreplacedyType, enreplacedy));
            }
            await Task.WhenAll(taskList).ConfigureAwait(false);

            var updateList = GetModifiedEnreplacedies(modificationList, ModificationKind.Update);
            taskList = new List<Task>(updateList.Count());
            foreach (var enreplacedy in updateList)
            {
                taskList.Add(UpdateEnreplacedyAsync(enreplacedyType, enreplacedy));
            }
            await Task.WhenAll(taskList).ConfigureAwait(false);

            var deleteList = GetModifiedEnreplacedies(modificationList, ModificationKind.Delete);
            taskList = new List<Task>(deleteList.Count());
            foreach (var enreplacedy in deleteList)
            {
                taskList.Add(DeleteAsync(enreplacedyType, enreplacedy));
            }
            await Task.WhenAll(taskList).ConfigureAwait(false);
        }

19 Source : UserOnlyStore.cs
with Apache License 2.0
from Aguafrommars

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

            var userId = ConvertIdToString(user.Id);

            var userClaims = await GetUserClaimsAsync(user).ConfigureAwait(false);
            var taskList = new List<Task>(claims.Count() + 1);
            foreach (var claim in claims)
            {
                userClaims.RemoveAll(uc => uc.ClaimType == claim.Type && uc.ClaimValue == claim.Value);
                taskList.Add(_db.HashDeleteAsync(UserClaimsKeyPrefix + claim.Type, userId));
            }

            taskList.Add(_db.HashSetAsync(UserClaimsRedisKey, userId, JsonConvert.SerializeObject(userClaims)));

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

19 Source : MediaManager.cs
with MIT License
from aguang-xyz

public async Task<IEnumerable<Episode>> SearchAsync(string word)
        {
            var tasks = _providers
                .Select(provider => GetEpisodesAsync(provider, word));
            
            return (await Task.WhenAll(tasks)).SelectMany(x => x);
        }

19 Source : DiscordShardedClient.cs
with MIT License
from Aiko-IT-Systems

public async Task StartAsync()
        {
            if (this._isStarted)
                throw new InvalidOperationException("This client has already been started.");

            this._isStarted = true;

            try
            {
                if (this.Configuration.TokenType != TokenType.Bot)
                    this.Logger.LogWarning(LoggerEvents.Misc, "You are logging in with a token that is not a bot token. This is not officially supported by Discord, and can result in your account being terminated if you aren't careful.");
                this.Logger.LogInformation(LoggerEvents.Startup, "Lib {0}, version {1}", this._botLibrary, this._versionString.Value);

                var shardc = await this.InitializeShardsAsync().ConfigureAwait(false);
                var connectTasks = new List<Task>();
                this.Logger.LogInformation(LoggerEvents.ShardStartup, "Booting {0} shards.", shardc);

                for (var i = 0; i < shardc; i++)
                {
                    //This should never happen, but in case it does...
                    if (this.GatewayInfo.SessionBucket.MaxConcurrency < 1)
                        this.GatewayInfo.SessionBucket.MaxConcurrency = 1;

                    if (this.GatewayInfo.SessionBucket.MaxConcurrency == 1)
                        await this.ConnectShardAsync(i).ConfigureAwait(false);
                    else
                    {
                        //Concurrent login.
                        connectTasks.Add(this.ConnectShardAsync(i));

                        if (connectTasks.Count == this.GatewayInfo.SessionBucket.MaxConcurrency)
                        {
                            await Task.WhenAll(connectTasks).ConfigureAwait(false);
                            connectTasks.Clear();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                await this.InternalStopAsync(false).ConfigureAwait(false);

                var message = $"Shard initialization failed, check inner exceptions for details: ";

                this.Logger.LogCritical(LoggerEvents.ShardClientError, $"{message}\n{ex}");
                throw new AggregateException(message, ex);
            }
        }

19 Source : DiscordShardedClient.cs
with MIT License
from Aiko-IT-Systems

public async Task UpdateStatusAsync(DiscordActivity activity = null, UserStatus? userStatus = null, DateTimeOffset? idleSince = null)
        {
            var tasks = new List<Task>();
            foreach (var client in this._shards.Values)
                tasks.Add(client.UpdateStatusAsync(activity, userStatus, idleSince));

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

19 Source : AsyncHelper.cs
with MIT License
from AiursoftWeb

public static Task ForEachParallel<T>(this IEnumerable<T> items, Func<T, Task> function)
            => Task.WhenAll(items
                .Select(function));

19 Source : Counter.Tests.cs
with MIT License
from AiursoftWeb

[TestMethod]
		public async Task TestCounter()
		{
			var counter = new Counter();
			replacedert.AreEqual(counter.GetCurrent, 0);
			var obj = new object();
			var numbers = new int[10000];
			var tasksList = new ConcurrentBag<Task>();
			for (int i = 0; i < 100; i++)
			{
				var task = Task.Run(() =>
				{
					for (int k = 0; k < 100; k++)
					{
						var uniqueNo = counter.GetUniqueNo();
						numbers[uniqueNo - 1]++;
					}
				});
				lock (obj)
				{
					tasksList.Add(task);
				}
			}
			await Task.WhenAll(tasksList);
			replacedert.AreEqual(counter.GetCurrent, 10000);
			replacedert.AreEqual(numbers.Max(), 1);
			replacedert.AreEqual(numbers.Min(), 1);
		}

19 Source : ConversationController.cs
with MIT License
from AiursoftWeb

[HttpPost]
        public async Task<IActionResult> UpdateMessageLifeTime(UpdateMessageLifeTimeAddressModel model)
        {
            var user = await GetKahlaUser();
            var target = await _dbContext
                .Conversations
                .Include(t => (t as GroupConversation).Users)
                .ThenInclude(t => t.User)
                .SingleOrDefaultAsync(t => t.Id == model.Id);
            if (target == null)
            {
                return this.Protocol(ErrorType.NotFound, $"Can not find conversation with id: {model.Id}.");
            }
            if (!target.HasUser(user.Id))
            {
                return this.Protocol(ErrorType.Unauthorized, "You don't have any relationship with that conversation.");
            }
            if (target is GroupConversation g && g.OwnerId != user.Id)
            {
                return this.Protocol(ErrorType.Unauthorized, "You are not the owner of that group.");
            }
            var oldestAliveTime = DateTime.UtcNow - TimeSpan.FromSeconds(Math.Min(target.MaxLiveSeconds, model.NewLifeTime));
            // Delete outdated for current.
            var toDelete = await _dbContext
                .Messages
                .Where(t => t.ConversationId == target.Id)
                .Where(t => t.SendTime < oldestAliveTime)
                .ToListAsync();
            _dbContext.Messages.RemoveRange(toDelete);
            await _dbContext.SaveChangesAsync();
            // Update current.
            target.MaxLiveSeconds = model.NewLifeTime;
            await _dbContext.SaveChangesAsync();
            var taskList = new ConcurrentBag<Task>();
            target.ForEachUser((eachUser, relation) =>
            {
                _kahlaPushService.TimerUpdatedEvent(eachUser, model.NewLifeTime, target.Id).Wait();
            });
            await Task.WhenAll(taskList);
            return this.Protocol(ErrorType.Success, "Successfully updated your life time. Your current message life time is: " +
                TimeSpan.FromSeconds(target.MaxLiveSeconds));
        }

19 Source : ThirdPartyPushService.cs
with MIT License
from AiursoftWeb

public Task PushAsync(IEnumerable<Device> devices, object payload, string triggerEmail = "[email protected]")
        {
            string vapidPublicKey = _configuration.GetSection("VapidKeys")["PublicKey"];
            string vapidPrivateKey = _configuration.GetSection("VapidKeys")["PrivateKey"];
            // Push to all devices.

            var pushTasks = new ConcurrentBag<Task>();
            foreach (var device in devices)
            {
                async Task PushToDevice()
                {
                    try
                    {
                        var pushSubscription = new PushSubscription(device.PushEndpoint, device.PushP256DH, device.PushAuth);
                        var vapidDetails = new VapidDetails("mailto:" + triggerEmail, vapidPublicKey, vapidPrivateKey);
                        var payloadToken = JsonConvert.SerializeObject(payload, new JsonSerializerSettings()
                        {
                            DateTimeZoneHandling = DateTimeZoneHandling.Utc,
                            ContractResolver = new CamelCasePropertyNamesContractResolver(),
                        });
                        await _webPushClient.SendNotificationAsync(pushSubscription, payloadToken, vapidDetails);
                    }
                    catch (WebPushException e)
                    {
                        _dbContext.Devices.Remove(device);
                        await _dbContext.SaveChangesAsync();
                        _logger.LogCritical(e, "An WebPush error occured while calling WebPush API: " + e.Message);
                        _logger.LogCritical(e, e.Message);
                    }
                    catch (Exception e)
                    {
                        _logger.LogCritical(e, "An error occured while calling WebPush API: " + e.Message);
                    }
                }
                pushTasks.Add(PushToDevice());
            }
            return Task.WhenAll(pushTasks);
        }

19 Source : Program.cs
with Apache License 2.0
from akovac35

public static async Task Main(string[] args)
        {
            SamplesLoggingHelper.LoggerInit(args, configActionNLog: () =>
            {
                NLogHelper.CreateLogger("NLog.config");
                LoggerFactoryProvider.LoggerFactory = NLogHelper.CreateLoggerFactory();
            }, configActionSerilog: () =>
            {
                SerilogHelper.CreateLogger(configure => configure.AddJsonFile("serilog.json", optional: false, reloadOnChange: true));
                LoggerFactoryProvider.LoggerFactory = SerilogHelper.CreateLoggerFactory();
            });

            Here(l => l.Entering(args));

            try
            {
                // Set correlationId for the current activity, it is preserved for the current thread and
                // across async/await
                using (Logger.BeginScope(new[] { new KeyValuePair<string, object>(Constants.CorrelationId, 12345678) }))
                {
                    List<Task<int>> tasks = new List<Task<int>>();
                    for (int i = 0; i < 10; i++)
                    {
                        tasks.Add(BusinessLogicMock<object>.GetTaskInstance(LoggerFactoryProvider.LoggerFactory));
                    }

                    // Business logic call sample
                    await Task.WhenAll(tasks);
                }

                Here(l => l.Exiting());
            }
            catch (Exception ex)
            {
                Here(l => l.LogError(ex, ex.Message));
                throw;
            }
            finally
            {
                SamplesLoggingHelper.LoggerConfig(configActionNLog: () =>
                {
                    NLogHelper.CloseAndFlushLogger();
                }, configActionSerilog: () =>
                {
                    SerilogHelper.CloseAndFlushLogger();
                });
            }
        }

19 Source : ObjectManager.cs
with MIT License
from alanedwardes

public async Task<IEnumerable<ResponseObject>> UploadObjects(IList<RequestObject> objects, CancellationToken token)
        {
            IEnumerable<Task<SignedBlob>> uploadUriTasks = objects.Select(ob => blobAdapter.UriForUpload(ob.Oid, ob.Size, token));

            SignedBlob[] signedBlobs = await Task.WhenAll(uploadUriTasks).ConfigureAwait(false);

            return objects.Select((ob, index) => new ResponseObject
            {
                Oid = ob.Oid,
                Size = ob.Size,
                Authenticated = true,
                Actions = new Actions
                {
                    Upload = new Action
                    {
                        Href = signedBlobs[index].Uri,
                        ExpiresIn = (long)signedBlobs[index].Expiry.TotalSeconds,
                        Headers = signedBlobs[index].Headers
                    }
                }
            });
        }

19 Source : KInMemoryPublisher.cs
with MIT License
from alethic

async Task PublishRunAsync(CancellationToken cancellationToken)
        {
            while (cancellationToken.IsCancellationRequested == false)
            {
                try
                {
                    logger.LogInformation("Initiating periodic publish of values.");
                    await Task.WhenAll(entries.Select(i => PublishValueAsync(i.Key, i.Value.Value, cancellationToken)));
                }
                catch (Exception e)
                {
                    logger.LogError(e, "Unexpected exception occurred publishing values.");
                }

                await Task.Delay(frequency, cancellationToken);
            }
        }

19 Source : KInMemoryStore.cs
with MIT License
from alethic

async Task ReplicateRunAsync(CancellationToken cancellationToken)
        {
            while (cancellationToken.IsCancellationRequested == false)
            {
                try
                {
                    List<Task> l = null;

                    using (slim.BeginUpgradableReadLock())
                    {
                        // continue while the first item is expired
                        while (
                            repQueue.Count > 0 &&
                            repQueue.FindMin() is Entry entry &&
                            entry.ReplicateTime != null &&
                            entry.ReplicateTime <= DateTime.UtcNow &&
                            entries.TryGetValue(entry.Key, out var record))
                        {
                            if (l == null)
                                l = new List<Task>();

                            using (slim.BeginWriteLock())
                            {
                                // schedule replication
                                l.Add(Task.Run(() => ReplicateAsync(entry, cancellationToken)));

                                // update to next time
                                entry.ReplicateTime = DateTime.UtcNow + frequency;

                                // remove existing queue entry
                                if (record.RepQueueHandle != null)
                                    repQueue.Delete(record.RepQueueHandle);

                                // add new queue entry
                                repQueue.Add(ref record.RepQueueHandle, entry);
                            }
                        }
                    }

                    // wait for all our replicate events to finish
                    if (l != null)
                        await Task.WhenAll(l);
                }
                catch (Exception e)
                {
                    logger.LogError(e, "Unexpected exception occurred republishing stored values.");
                }

                await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);
            }
        }

19 Source : KLookup.cs
with MIT License
from alethic

async ValueTask<LookupResult> LookupAsync(TNodeId key, FindFunc func, CancellationToken cancellationToken = default)
        {
            if (func is null)
                throw new ArgumentNullException(nameof(func));

            var wait = new HashSet<Task<FindResult>>();
            var comp = new KNodeIdDistanceComparer<TNodeId>(key);

            // kill is used to cancel outstanding tasks early
            var kill = new CancellationTokenSource();
            var stop = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, kill.Token);

            // find our own closest peers to seed from
#if NETSTANDARD2_1
            var init = router.SelectAsync(key, alpha, cancellationToken);
#else
            var init = await router.SelectAsync(key, alpha, cancellationToken);
#endif

            // tracks the peers remaining to query sorted by distance
            var todo = new C5.IntervalHeap<KNodeEndpointInfo<TNodeId>>(router.K, new FuncComparer<KNodeEndpointInfo<TNodeId>, TNodeId>(i => i.Id, comp));
#if NETSTANDARD2_1
            await foreach (var i in init)
                todo.Add(i);
#else
            todo.AddAll(init);
#endif

            // track done nodes so we don't recurse; and maintain a list of near nodes that have been traversed
            var done = new HashSet<TNodeId>(todo.Select(i => i.Id));
            var path = new C5.IntervalHeap<KNodeEndpointInfo<TNodeId>>(router.K, new FuncComparer<KNodeEndpointInfo<TNodeId>, TNodeId>(i => i.Id, comp));

            try
            {
                // continue until all work is completed
                while (todo.Count > 0 || wait.Count > 0)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    // schedule queries of our closest nodes
                    while (wait.Count < alpha && todo.Count > 0)
                    {
                        // schedule new node to query
                        var peer = todo.DeleteMin();
                        if (peer.Id.Equals(host.SelfId) == false)
                            wait.Add(func(peer, key, stop.Token).AsTask().ContinueWith((r, o) => r.Result, peer, TaskContinuationOptions.OnlyOnRanToCompletion));
                    }

                    // we have at least one task in the task pool to wait for
                    if (wait.Count > 0)
                    {
                        // wait for first finished task
                        var find = await TaskWhenAny(wait);
                        wait.Remove(find);

                        // skip cancelled tasks
                        if (find.IsCanceled)
                            continue;

                        // skip failed tasks
                        if (find.Exception != null)
                        {
                            // ignore various cancellation exceptions
                            if (find.Exception.InnerException is TimeoutException)
                                continue;
                            if (find.Exception.InnerException is OperationCanceledException)
                                continue;

                            logger.LogError(find.Exception, "Received error from lookup task.");
                            continue;
                        }

                        // extract the peer this request was destined to
                        var peer = (KNodeEndpointInfo<TNodeId>)find.AsyncState;

                        // method returned the value; we can stop looking and return the value and our path
                        if (find.Result.Value != null)
                            return new LookupResult(key, path, peer, find.Result.Value);

                        // task returned more peers, lets begin working on them
                        if (find.Result.Nodes != null)
                        {
                            // after we've received a successful result
                            // mark the node as one we've encountered which did not return a value
                            path.Add(peer);

                            // path should only contain top K nodes
                            while (path.Count > router.K)
                                path.DeleteMax();

                            // iterate over newly retrieved peers
                            foreach (var i in find.Result.Nodes)
                            {
                                // received node is closer than current
                                if (i.Id.Equals(host.SelfId) == false)
                                {
                                    if (done.Add(i.Id))
                                    {
                                        todo.Add(i);

                                        // remove uninteresting nodes
                                        while (todo.Count > router.K)
                                            todo.DeleteMax();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            finally
            {
                // signal any remaining tasks to exit immediately
                kill.Cancel();

                try
                {
                    // clean up and capture results of outstanding
                    if (wait.Count > 0)
                    {
                        logger.LogDebug("Cancelling {Count} outstanding requests.", wait.Count);
                        await Task.WhenAll(wait);
                    }
                }
                catch (OperationCanceledException)
                {
                    // ignore
                }
            }

            // we never found anything; return the path we took, but that's it
            return new LookupResult(key, path, null, null);
        }

19 Source : EnumerableExtensions.cs
with MIT License
from AlexanderFroemmgen

public static async Task<IEnumerable<TResult>> SelectManyAsync<TSource, TResult>(
            this IEnumerable<TSource> source, Func<TSource, Task<IEnumerable<TResult>>> selector)
        {
            var results = await Task.WhenAll(source.Select(selector));
            return results.SelectMany(r => r);
        }

19 Source : BankTest.cs
with Apache License 2.0
from AlexandreDaSilva

[Test]
        public async Task test_bank()
        {
            await CreateAccounts();

            var totalTask = Task.Run(() => RunTotalInLoop());

            var txnTask = Task.WhenAll(Enumerable.Range(0, 10)
                .Select(_ => Task.Run(() => TxnLoop())));

            if (!txnTask.Wait(1000 * 60 * 5))
            {
                Console.WriteLine("Timeout elapsed");
            }

            totalTask.Wait(1000 * 5);
        }

19 Source : AcctUpsertTest.cs
with Apache License 2.0
from AlexandreDaSilva

private async Task DoUpserts()
        {
            var tasks = new List<Task>();

            foreach (var a in _accounts)
            {
                tasks.AddRange(Enumerable
                    .Range(0, 5)
                    .Select(_ => Task.Run(() => Upsert(a))));
            }

            await Task.WhenAll(tasks);
        }

19 Source : RateManager.cs
with MIT License
from alexeybusygin

private async Task<Shipment> GetRates(Shipment shipment)
        {
            // create an ArrayList of threads, pre-sized to the number of providers.
            var threads = new List<Task>();

            // iterate through the providers.
            foreach (AbstractShippingProvider provider in _providers)
            {
                // replacedign the shipment to the provider.
                provider.Shipment = shipment;
                // 
                threads.Add(provider.GetRates());
            }

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

            // return our Shipment instance.
            return shipment;
        }

19 Source : HateoasResultProvider.cs
with Apache License 2.0
from alexz76

public async Task<IActionResult> GetContentResultAsync(ObjectResult result)
		{
			var policies = GetFilteredPolicies(result);
			if (!policies.Any())
			{
				return null;
			}

			var content = default(JsonResult);

			async Task<IList<object>> GetLinksAsync(object item)
			{
				var links = new List<object>();

				foreach (var policy in policies.Where(p => p != null))
				{
					var lambdaResult = GetLambdaResult(policy.Expression, item);
					var link = await GetPolicyLinkAsync(policy, lambdaResult).ConfigureAwait(false);
					links.Add(link);
				}

				return links;
			}

			async Task<object> GetFinalJsonPayloadAsync(object item)
			{
				var links = await GetLinksAsync(item).ConfigureAwait(false);

				return await Task.FromResult(item.ToFinalPayload(links)).ConfigureAwait(false);
			}

			if (result.Value is IEnumerable<object> collection)
			{
				var links = await Task.WhenAll(collection.Select(item => GetFinalJsonPayloadAsync(item))).ConfigureAwait(false);
				var json = new List<object>(links);

				content = new JsonResult(json);
			}
			else
			{
				var links = await GetFinalJsonPayloadAsync(result.Value).ConfigureAwait(false);
				content = new JsonResult(links);
			}

			return await Task.FromResult(content).ConfigureAwait(false);
		}

19 Source : DefaultLogServiceClientBenchmark.cs
with MIT License
from aliyun

[BenchmarkCategory("PostLogStoreLogs")]
        [Benchmark(OperationsPerInvoke = 10)]
        public async Task PostLogStoreLogs_10Parallel()
        {
            await Task.WhenAll(Enumerable.Range(0, 10)
                .Select(async i =>
                    await this.client.PostLogStoreLogsAsync(this.logstoreName, this.logGroup)));
        }

19 Source : ParallelScanAsyncEnumerator.cs
with MIT License
from AllocZero

public async ValueTask DisposeAsync()
        {
            _cts.Cancel();
            _cts.Dispose();

            try
            {
                await Task.WhenAll(_tasks).ConfigureAwait(false);
            }
            catch (OperationCanceledException)
            {
            }
        }

19 Source : DatabricksRestClient.cs
with Apache License 2.0
from aloneguid

public async Task<IReadOnlyCollection<Job>> ListAllJobs(bool includeRuns)
      {
         var request = new HttpRequestMessage(HttpMethod.Get, $"{_apiBase20}/jobs/list");
         HttpResponseMessage response = await SendAsync(request);
         response.EnsureSuccessStatusCode();
         string rjson = await response.Content.ReadreplacedtringAsync();
         JobListResponse jobListResponse = JsonSerializer.Deserialize<JobListResponse>(rjson);

         if((jobListResponse?.Jobs?.Length ?? 0) == 0)
            return new List<Job>();

         if(includeRuns)
         {
            RunsListResponse[] listOfListOfRuns = await Task.WhenAll(jobListResponse.Jobs.Select(rj => ListJobRuns(rj.Id, 2)));
            return jobListResponse.Jobs.Zip(listOfListOfRuns, (job, runs) =>
            {
               if(runs?.Runs != null)
               {
                  job.Runs.AddRange(runs.Runs);
               }
               return job;
            }).ToList();
         }

         return jobListResponse.Jobs.ToList();
      }

19 Source : DefaultRedisProvider.Async.cs
with MIT License
from AlphaYu

protected override async Task BaseSetAllAsync<T>(IDictionary<string, T> values, TimeSpan expiration)
        {
            ArgumentCheck.NotNegativeOrZero(expiration, nameof(expiration));
            ArgumentCheck.NotNullAndCountGTZero(values, nameof(values));

            var tasks = new List<Task>();

            foreach (var item in values)
                tasks.Add(SetAsync(item.Key, item.Value, expiration));

            await Task.WhenAll(tasks);
        }

19 Source : DefaultRedisProvider.Async.cs
with MIT License
from AlphaYu

protected override async Task BaseFlushAsync()
        {
            if (_cacheOptions.EnableLogging)
                _logger?.LogInformation("Redis -- FlushAsync");

            var tasks = new List<Task>();

            foreach (var server in _servers)
            {
                tasks.Add(server.FlushDatabaseAsync(_redisDb.Database));
            }

            await Task.WhenAll(tasks);
        }

19 Source : ResourceLoader.cs
with MIT License
from AlternateLife

public Task Start()
        {
            var startTasks = new List<Task>();

            foreach (var resource in _resources)
            {
                startTasks.Add(Task.Run(() => resource.Start()));
            }

            return Task.WhenAll(startTasks);
        }

19 Source : SasTokenProviderTests.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

[Fact]
        public async Task GetSasToken_Mulreplacedhread()
        {
            // Arrange
            string org_ttd = "ttd";
            string uri_ttd = string.Format(KeyVaultURI, org_ttd);

            string storageAccount_ttd = string.Format(StorageAccount, org_ttd);
            string sasDefinition_ttd = string.Format(SasDefinition, org_ttd);
            string secretName_ttd = $"{storageAccount_ttd}-{sasDefinition_ttd}";

            string org_brg = "brg";
            string uri_brg = string.Format(KeyVaultURI, org_brg);

            string storageAccount_brg = string.Format(StorageAccount, org_brg);
            string sasDefinition_brg = string.Format(SasDefinition, org_brg);
            string secretName_brg = $"{storageAccount_brg}-{sasDefinition_brg}";

            Mock<IKeyVaultClientWrapper> keyVaultClient = new Mock<IKeyVaultClientWrapper>();
            keyVaultClient.Setup(s => s.GetSecretAsync(It.IsAny<string>(), It.Is<string>(i => i == secretName_ttd))).ReturnsAsync("ttdsecret");
            keyVaultClient.Setup(s => s.GetSecretAsync(It.IsAny<string>(), It.Is<string>(i => i == secretName_brg))).ReturnsAsync("brgsecret");

            SasTokenProvider target = new SasTokenProvider(keyVaultClient.Object, _storageConfiguration.Object, _mockLogger.Object);

            // Act
            ManualResetEvent mre = new ManualResetEvent(false);
            List<Task> tasks = new List<Task>();
            for (int i = 0; i < 5; i++)
            {
                Task task1 = Task.Run(async () =>
                {
                    mre.WaitOne();
                    await target.GetSasToken(org_ttd);
                });

                tasks.Add(task1);

                Task task2 = Task.Run(async () =>
                {
                    mre.WaitOne();
                    await target.GetSasToken(org_brg);
                });

                tasks.Add(task2);
            }

            // Run all tasks.
            mre.Set();
            await Task.WhenAll(tasks);

            string ttdSecret = await target.GetSasToken(org_ttd);
            string brgSecret = await target.GetSasToken(org_brg);

            // replacedert
            replacedert.Equal("ttdsecret", ttdSecret);
            replacedert.Equal("brgsecret", brgSecret);

            keyVaultClient.Verify(s => s.GetSecretAsync(It.Is<string>(u => u == uri_ttd), It.Is<string>(i => i == secretName_ttd)), Times.Once);
            keyVaultClient.Verify(s => s.GetSecretAsync(It.Is<string>(u => u == uri_brg), It.Is<string>(i => i == secretName_brg)), Times.Once);
        }

See More Examples