-
-
Save kkozmic/670019 to your computer and use it in GitHub Desktop.
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 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