Created
October 31, 2014 06:02
-
-
Save revirth/c2146219ceb6930098df to your computer and use it in GitHub Desktop.
using Paralle.ForEach to DataTable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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