public static async Task <int[]> MergeSort_Recursive(int[] numbers, int threshold) { if (numbers.Length <= 1) { return(numbers); } int lengthLeft = numbers.Length / 2; int lengthRight = numbers.Length - lengthLeft; int[] leftResult; int[] rightResult; if (lengthLeft < threshold) { int[] left = new int[lengthLeft]; Array.Copy(numbers, left, lengthLeft); leftResult = MergeSort_Serial.MergeSort_Recursive(left); } else { leftResult = await Task <int[]> .Run(async() => { int[] left = new int[lengthLeft]; Array.Copy(numbers, left, lengthLeft); return(await MergeSort_Recursive(left, threshold)); }); } if (lengthRight < threshold) { int[] right = new int[lengthRight]; Array.Copy(numbers, lengthLeft, right, 0, lengthRight); rightResult = MergeSort_Serial.MergeSort_Recursive(right); } else { rightResult = await Task <int[]> .Run(async() => { int[] right = new int[lengthRight]; Array.Copy(numbers, lengthLeft, right, 0, lengthRight); return(await MergeSort_Recursive(right, threshold)); }); } return(Merge(leftResult, rightResult)); }
private static void MergeSort_Run(int[] numbers, int th1, int th2, int th3) { Stopwatch sw_serial = new Stopwatch(); sw_serial.Start(); var result_serial = MergeSort_Serial.MergeSort_Recursive(numbers); sw_serial.Stop(); var serialTimeTaken = sw_serial.ElapsedMilliseconds; Task[] tasks = new Task[4]; Stopwatch sw_parallel = new Stopwatch(); sw_parallel.Start(); int[] result_parallel; long parallelTimeTaken = 0; tasks[0] = MergeSort_Parallel.MergeSort_Recursive(numbers).ContinueWith(x => { result_parallel = x.Result; sw_parallel.Stop(); parallelTimeTaken = sw_parallel.ElapsedMilliseconds; }); Task.WaitAll(tasks[0]); Stopwatch sw_par_th1 = new Stopwatch(); sw_par_th1.Start(); int[] result_parallel_TH1; long parallelTH1TimeTaken = 0; tasks[1] = MergeSort_Parallel_TH.MergeSort_Recursive(numbers, th1).ContinueWith(x => { result_parallel_TH1 = x.Result; sw_par_th1.Stop(); parallelTH1TimeTaken = sw_par_th1.ElapsedMilliseconds; }); Task.WaitAll(tasks[1]); Stopwatch sw_par_th2 = new Stopwatch(); sw_par_th2.Start(); int[] result_parallel_TH2; long parallelTH2TimeTaken = 0; tasks[2] = MergeSort_Parallel_TH.MergeSort_Recursive(numbers, th2).ContinueWith(x => { result_parallel_TH2 = x.Result; sw_par_th2.Stop(); parallelTH2TimeTaken = sw_par_th2.ElapsedMilliseconds; }); Task.WaitAll(tasks[2]); Stopwatch sw_par_th3 = new Stopwatch(); sw_par_th3.Start(); int[] result_parallel_TH3; long parallelTH3TimeTaken = 0; tasks[3] = MergeSort_Parallel_TH.MergeSort_Recursive(numbers, th3).ContinueWith(x => { result_parallel_TH3 = x.Result; sw_par_th3.Stop(); parallelTH3TimeTaken = sw_par_th3.ElapsedMilliseconds; }); Task.WaitAll(tasks[3]); Console.WriteLine("MergeSort:\n\t Serial time taken: {0},\n\t Parallel time taken: {1},\n\t Parallel_TH-{2}: time taken: {3},\n\t Parallel_TH-{4}: time taken: {5},\n\t Parallel_TH-{6}: time taken: {7}", serialTimeTaken, parallelTimeTaken, th1, parallelTH1TimeTaken, th2, parallelTH2TimeTaken, th3, parallelTH3TimeTaken); }