Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment