// Copyright Epic Games, Inc. All Rights Reserved. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; namespace EpicGames.Core { /// /// Async equivalents for parallel methods /// public static class ParallelTask { /// /// Execute a large number of tasks in parallel over a collection. Parallel.ForEach() method isn't generally compatible with asynchronous programming, because any /// exceptions are thrown on the /// /// The starting index /// The last index, exclusive /// Action to perform for each item in the collection /// Async task public static Task ForAsync(int fromInclusive, int toExclusive, Action action) { return ForEachAsync(Enumerable.Range(fromInclusive, toExclusive - fromInclusive), action); } /// /// Execute a large number of tasks in parallel over a collection. Parallel.ForEach() method isn't generally compatible with asynchronous programming, because any /// exceptions are thrown on the /// /// The collection type /// The collection to iterate over /// Action to perform for each item in the collection /// Async task public static Task ForEachAsync(IEnumerable collection, Action action) { ExecutionDataflowBlockOptions options = new ExecutionDataflowBlockOptions(); options.MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded; ActionBlock actions = new ActionBlock(action, options); foreach (T item in collection) { actions.Post(item); } actions.Complete(); return actions.Completion; } /// /// Execute a large number of tasks in parallel over a collection. Parallel.ForEach() method isn't generally compatible with asynchronous programming, because any /// exceptions are thrown on the /// /// The collection type /// The collection to iterate over /// Action to perform for each item in the collection /// Maximum degree of parallelism /// Async task public static Task ForEachAsync(IEnumerable collection, Func action, int maxDegreeOfParallelism) { ExecutionDataflowBlockOptions options = new ExecutionDataflowBlockOptions(); options.MaxDegreeOfParallelism = maxDegreeOfParallelism; ActionBlock actions = new ActionBlock(action, options); foreach (T item in collection) { actions.Post(item); } actions.Complete(); return actions.Completion; } } }