// Copyright Epic Games, Inc. All Rights Reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
}
}
}