Tuesday, December 27, 2011

Cathing exceptions in pararlel for

private static void ProcessDataInParallel(byte[] data) { // Use ConcurrentQueue to enable safe enqueueing from multiple threads. var exceptions = new ConcurrentQueue<Exception>(); // Execute the complete loop and capture all exceptions. Parallel.ForEach(data, d => { try { // Cause a few exceptions, but not too many. if (d < 0x3) throw new ArgumentException(String.Format("value is {0:x}. Elements must be greater than 0x3.", d)); else Console.Write(d + " "); } // Store the exception and continue with the loop. catch (Exception e) { exceptions.Enqueue(e); } }); // Throw the exceptions here after the loop completes. if (exceptions.Count > 0) throw new AggregateException(exceptions); }

Parallel for

int[] nums = Enumerable.Range(0, 1000000).ToArray(); int[] results = new int[nums.Length]; Parallel.For(0, nums.Length, (i,loopsatate) => { if (i < 100) results[i] = 2 * nums[i]; else { loopsatate.Stop(); return; } } );

Struct larda aynı yere iki değişkenle bakmak

[StructLayout(LayoutKind.Explicit)] struct TestExplicit { [FieldOffset(0)] public long lg; [FieldOffset(0)] public int i1; [FieldOffset(4)] public int i2; } public static void Main(string[] args) { TestExplicit t = new TestExplicit(); t.lg = long.MaxValue; int a = t.i1; int b = t.i2; }