|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Threading.Tasks;
namespace InParallel
{
class Run
{
public static void Main(string[] args)
{
Tree myTree = CreateTree(15, 2);
Console.WriteLine("Press Enter to Run Sequential Sample");
Console.Read();
Console.WriteLine("Started");
Stopwatch watch = Stopwatch.StartNew();
WalkTree(myTree);
watch.Stop();
Console.WriteLine("End");
Console.WriteLine("Total Time Taken Sequential " + watch.ElapsedMilliseconds.ToString());
GC.Collect();
//Gives memory out exception
/*
Console.WriteLine("Press Enter to Run Threads Sample");
Console.Read();
Console.WriteLine("Started");
watch = Stopwatch.StartNew();
WalkTreeUsingThreads(myTree);
watch.Stop();
Console.WriteLine("End");
Console.WriteLine("Total Time Taken using Threads " + watch.ElapsedMilliseconds.ToString());
GC.Collect();
*/
Console.WriteLine("***************");
Console.WriteLine("Press Enter to Run Tasks Sample");
Console.ReadLine();
Console.WriteLine("Started");
Console.WriteLine("*** Watch the fun at in Your Task Manager\\Performance Tab. CPU now should be 100%");
watch = Stopwatch.StartNew();
WalkTreeUsingTasks(myTree);
watch.Stop();
Console.WriteLine("End");
Console.WriteLine("Total Time Taken using Tasks " + watch.ElapsedMilliseconds.ToString());
Console.ReadLine();
}
static Tree CreateTree(int depth, int start)
{
Tree root = new Tree();
root.Data = start;
if (depth > 0)
{
root.Left = CreateTree(depth - 1, start + 1);
root.Right = CreateTree(depth - 1, start + 1);
}
return root;
}
static void WalkTree(Tree treeToWalk)
{
if (treeToWalk == null) return;
WalkTree(treeToWalk.Left);
WalkTree(treeToWalk.Right);
ProcessItem(treeToWalk.Data);
}
static void WalkTreeUsingThreads(Tree treeToWalk)
{
if (treeToWalk == null) return;
Thread leftThread = new Thread(()=>WalkTreeUsingThreads(treeToWalk.Left));
leftThread.Start();
Thread rightThread = new Thread(() => WalkTreeUsingThreads(treeToWalk.Right));
rightThread.Start();
leftThread.Join();
rightThread.Join();
ProcessItem(treeToWalk.Data);
}
static void WalkTreeUsingTasks(Tree treeToWalk)
{
if (treeToWalk == null) return;
Task left = new Task(() => WalkTreeUsingTasks(treeToWalk.Left));
left.Start();
Task right = new Task(() => WalkTreeUsingTasks(treeToWalk.Right));
right.Start();
left.Wait();
right.Wait();
ProcessItem(treeToWalk.Data);
}
static void ProcessItem(int Data)
{
Thread.SpinWait(100000);
}
}
class Tree
{
public Tree Left = null;
public Tree Right = null;
public int Data=0;
}
}
|
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.