Skip to content

Instantly share code, notes, and snippets.

@revirth
Created October 31, 2014 06:02
Show Gist options
  • Save revirth/c2146219ceb6930098df to your computer and use it in GitHub Desktop.
Save revirth/c2146219ceb6930098df to your computer and use it in GitHub Desktop.
using Paralle.ForEach to DataTable
[DllImport("kernel32.dll")]
static extern int GetCurrentProcessorNumber();
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("n", typeof(int));
var numbers = Enumerable.Range(0, 1000);
Stopwatch sw = new Stopwatch();
sw.Start();
Parallel.ForEach(numbers, n => {
StartParallelSum(n, dt);
});
sw.Stop();
Console.WriteLine("0 to " + numbers.Max() + ", " +
sw.ElapsedMilliseconds.ToString() + "ms");
}
private static void StartParallelSum(int n, DataTable dt)
{
DataRow dr;
lock (dt.Rows.SyncRoot) {
dr = dt.NewRow();
dr["n"] = Guid.NewGuid().ToString().Length;
dt.Rows.Add(dr);
}
Console.WriteLine("on thread {0:d2} / on process {1}/{2} - {3}",
Thread.CurrentThread.ManagedThreadId,
GetCurrentProcessorNumber(),
Environment.ProcessorCount, n);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment