Guest User

Untitled

a guest
Jun 21st, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. public class AsyncHelper
  2. {
  3. private volatile bool allDone = false;
  4. private volatile int doneCount = 0;
  5. private int actionsCount;
  6. private ICollection<Exception> exceptions = new List<Exception>();
  7.  
  8. public bool ExecuteInParallel(params System.Action[] actions)
  9. {
  10. if (actions == null || actions.Length == 0) return false;
  11.  
  12. actionsCount = actions.Length;
  13.  
  14. foreach (var action in actions) {
  15. action.BeginInvoke(result => ProcessAsyncCallback(result, actionStatus), action);
  16. }
  17.  
  18. while (alldone == false) {
  19. // do nothing or perhaps Thread.SpinWait();
  20. }
  21. // perhaps throw the exception(s) ?
  22. return exceptions.Count == 0;
  23. }
  24.  
  25. private void ProcessAsyncCallback(IAsyncResult result, IDictionary<System.Action, bool> actionStatus)
  26. {
  27. var originatingAction = (System.Action)result.AsyncState;
  28.  
  29. try {
  30. originatingAction.EndInvoke(result);
  31. }
  32. catch (Exception exception) {
  33. Trace.TraceError(exception.ToString());
  34. exceptions.Add(exception);
  35. }
  36. finally {
  37. if(Interlocked.Increment(ref doneCount) == actionsCount)
  38. {
  39. allDone = true;
  40. }
  41. }
  42. }
  43. }
Add Comment
Please, Sign In to add comment