Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- namespace Core.Threading {
- /// <summary>
- /// Used for .net v3.5
- /// </summary>
- public static class ActionExtensions {
- public static void ExecAllAndWait(this IEnumerable<Action> actions,TimeSpan timeout) {
- WaitHandle[] waitHandles = new WaitHandle[actions.Count()];
- int i = 0;
- foreach(var action in actions) {
- waitHandles[i++] = action.BeginInvoke(null,null).AsyncWaitHandle;
- }
- WaitAll(waitHandles,timeout);
- }
- public static List<WaitHandle> ExecAsync(this IEnumerable<Action> actions) {
- List<WaitHandle> waitHandles = new List<WaitHandle>();
- foreach(var action in actions) {
- AutoResetEvent waitHandle = new AutoResetEvent(false);
- waitHandles.Add(waitHandle);
- ActionHandler commandExecsHandler = new ActionHandler(action,waitHandle);
- ThreadPool.QueueUserWorkItem((state) => {
- ((ActionHandler)state).Execute();
- },commandExecsHandler);
- }
- return waitHandles;
- }
- public static bool WaitAll(this List<WaitHandle> waitHandles,int timeoutMs) {
- return WaitAll(waitHandles.ToArray(),timeoutMs);
- }
- public static bool WaitAll(this ICollection<WaitHandle> waitHandles,int timeoutMs) {
- return WaitAll(waitHandles.ToArray(),timeoutMs);
- }
- public static bool WaitAll(this ICollection<WaitHandle> waitHandles,TimeSpan timeout) {
- return WaitAll(waitHandles.ToArray(),(int)timeout.TotalMilliseconds);
- }
- public static bool WaitAll(this List<IAsyncResult> asyncResults,TimeSpan timeout) {
- var waitHandles = asyncResults.ConvertAll(x => x.AsyncWaitHandle);
- return WaitAll(waitHandles.ToArray(),(int)timeout.TotalMilliseconds);
- }
- public static bool WaitAll(WaitHandle[] waitHandles,TimeSpan timeout) {
- return WaitAll(waitHandles,(int)timeout.TotalMilliseconds);
- }
- public static bool WaitAll(WaitHandle[] waitHandles,int timeOutMs) {
- if(waitHandles == null)
- throw new ArgumentNullException("waitHandles");
- if(waitHandles.Length == 0)
- return true;
- if(Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) {
- // WaitAll for multiple handles on an STA thread is not supported.
- // CurrentThread is ApartmentState.STA when run under unit tests
- var successfullyComplete = true;
- foreach(var waitHandle in waitHandles) {
- successfullyComplete = successfullyComplete
- && waitHandle.WaitOne(timeOutMs,false);
- }
- return successfullyComplete;
- }
- return WaitHandle.WaitAll(waitHandles,timeOutMs,false);
- }
- class ActionHandler {
- public Action ActionExecute { get; private set; }
- public WaitHandle Handle { get; private set; }
- public void Execute() {
- ActionExecute();
- }
- public ActionHandler(Action a,WaitHandle h) {
- ActionExecute = a;
- Handle = h;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment