|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Diagnostics;
static class ActionExtensions
{
class WaitList : IDisposable
{
readonly List<IAsyncResult> waits = new List<IAsyncResult>();
public void Add(IAsyncResult ar)
{
waits.Add(ar);
}
public void Dispose()
{
foreach (var ar in waits)
{
ar.AsyncWaitHandle.WaitOne();
}
}
}
public static Action MakeParallel(this Action t)
{
return () =>
{
using (var w = new WaitList())
{
foreach (Action a in t.GetInvocationList())
{
w.Add(a.BeginInvoke(null, null));
}
}
};
}
public static Action<T1> MakeParallel<T1>(this Action<T1> t)
{
return (x) =>
{
using (var w = new WaitList())
{
foreach (Action<T1> a in t.GetInvocationList())
{
w.Add(a.BeginInvoke(x, null, null));
}
}
};
}
public static Action<T1, T2> MakeParallel<T1, T2>(this Action<T1, T2> t)
{
return (x, y) =>
{
using (var w = new WaitList())
{
foreach (Action<T1, T2> a in t.GetInvocationList())
{
w.Add(a.BeginInvoke(x, y, null, null));
}
}
};
}
public static Action<T1, T2, T3> MakeParallel<T1, T2, T3>(this Action<T1, T2, T3> t)
{
return (x, y, z) =>
{
using (var w = new WaitList())
{
foreach (Action<T1, T2, T3> a in t.GetInvocationList())
{
w.Add(a.BeginInvoke(x, y, z, null, null));
}
}
};
}
public static Action<T1, T2, T3, T4> MakeParallel<T1, T2, T3, T4>(this Action<T1, T2, T3, T4> t)
{
return (x, y, z, v) =>
{
using (var w = new WaitList())
{
foreach (Action<T1, T2, T3, T4> a in t.GetInvocationList())
{
w.Add(a.BeginInvoke(x, y, z, v, null, null));
}
}
};
}
}
class Program
{
static void Main(string[] args)
{
Action<int> f = null;
for (int i = 0; i < 8; i++)
{
f += Thread.Sleep;
}
Stopwatch ws = Stopwatch.StartNew();
f(250);
Console.WriteLine("ser: {0:f3}", ws.Elapsed.TotalMilliseconds);
f = f.MakeParallel();
ws = Stopwatch.StartNew();
f(250);
Console.WriteLine("par: {0:f3}", ws.Elapsed.TotalMilliseconds);
Console.ReadLine();
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.