Created
November 9, 2010 23:06
-
-
Save thomasjo/670014 to your computer and use it in GitHub Desktop.
Very naïve implemention of parallelization in C# 3.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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