/* ** Method Name: StartTaskSpawner() ** Parameters: None. ** Return Values: Void. ** Description: This method is used to spawn (start/create) a worker task that will continue to loop until the _StopFlag is changed to true. ** The task can be paused with the _PauseFlag. When operating in active mode it constantly generates lines and passes them to the UI thread's dispatcher. ** The task will allow lines to remain on the screen according to the _TailLength variable, lines beyond this value will be removed. ** After the line has been drawn the task sleeps for a time determined by the value of _SleepTimeInMilliSeconds. ** Also, a reference to the task will be placed into the list called TaskPool, so it can be referenced later. */ public void StartTaskSpawner() { LineGenerator myLineGenerator = new LineGenerator(); Brush ThreadColour = GetRandomBrushColour(); // Spawning the task (thread) that will perform the work of constantly generating new lines and sending them to the UI thread. Can be stopped via _StopFlag. Task t = Task.Run(() => { Queue <Line> LineQue = new Queue <Line>(); while (_StopFlag == false) { while (_PauseFlag == true) { Thread.Sleep(_SpawnTimeInMilliSeconds); } // I am putting this check in to ensure that no more lines are drawn once the stop flag has tripped. if (_StopFlag == true) { break; } // This use of the dispatcher is necessary to have the UI thread access and told to draw the lines that we are generating. ActiveCanvas.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, (Action)(() => { // Generate a new line. Line myLine = new Line(); myLineGenerator.CalculateNewLinePoints(myLine); myLine.Stroke = ThreadColour; // Add the line to the collection of elements for the ActiveCanvas. ActiveCanvas.Children.Add(myLine); // Add the line to the que of lines. LineQue.Enqueue(myLine); // This code clears up the extra lines, once the desired number of tails has been reached. while (LineQue.Count >= (_TailLength + 1)) { ActiveCanvas.Children.Remove(LineQue.Dequeue()); } })); // This sleep command determines how fast the lines are generated, reducing the time here equals faster line generation. Thread.Sleep(_SpawnTimeInMilliSeconds); } }); TaskPool.Add(t); }