Skip to content

Instantly share code, notes, and snippets.

@kkozmic
Forked from thomasjo/Parallelizer.cs
Created November 9, 2010 23:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kkozmic/670019 to your computer and use it in GitHub Desktop.
Save kkozmic/670019 to your computer and use it in GitHub Desktop.
public class AsyncHelper
{
private volatile bool allDone = false;
private volatile int doneCount = 0;
private int actionsCount;
private ICollection<Exception> exceptions = new List<Exception>();
public bool ExecuteInParallel(params System.Action[] actions)
{
if (actions == null || actions.Length == 0) return false;
actionsCount = actions.Length;
foreach (var action in actions) {
action.BeginInvoke(result => ProcessAsyncCallback(result, actionStatus), action);
}
while (alldone == false) {
// do nothing or perhaps Thread.SpinWait();
}
// perhaps throw the exception(s) ?
return exceptions.Count == 0;
}
private void ProcessAsyncCallback(IAsyncResult result, IDictionary<System.Action, bool> actionStatus)
{
var originatingAction = (System.Action)result.AsyncState;
try {
originatingAction.EndInvoke(result);
}
catch (Exception exception) {
Trace.TraceError(exception.ToString());
exceptions.Add(exception);
}
finally {
if(Interlocked.Increment(ref doneCount) == actionsCount)
{
allDone = true;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment