Skip to content

Instantly share code, notes, and snippets.

@thomasjo
Created November 9, 2010 23:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thomasjo/670014 to your computer and use it in GitHub Desktop.
Save thomasjo/670014 to your computer and use it in GitHub Desktop.
Very naïve implemention of parallelization in C# 3.
public class Parallelizer
{
private int actionCount;
private int completedActionsCount;
private volatile bool allActionsCompleted;
private ICollection<Exception> exceptions;
public IEnumerable<Exception> Exceptions
{
get { return exceptions; }
}
public bool ExecuteInParallel(params System.Action[] actions)
{
if (actions == null || actions.Length == 0) return false;
actionCount = actions.Length;
completedActionsCount = 0;
allActionsCompleted = false;
exceptions = new List<Exception>();
foreach (var action in actions) {
action.BeginInvoke(result => ProcessAsyncCallback(result), action);
}
while (!allActionsCompleted) {
Thread.Sleep(50); // NOTE: This number was chosen arbitrarily. Should probably approach this more scientifically.
}
return exceptions.Count == 0;
}
private void ProcessAsyncCallback(IAsyncResult result)
{
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 completedActionsCount) == actionCount) {
allActionsCompleted = true;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment