C#: First utilize reliable Timers to simulate multitasking

Using reliable timers is the simplest way to simulate multitasking. I consider this “simulating” multitasking since the code that is essentially on hold waiting for the Timer (Timer Work in the image below) to expire is not really doing any work. I say “reliable” timers because they are just that: you declare one, specify its timeout (in milliseconds), and set the method to execute when the timer “fires.” It’s just waiting for time to pass. In a more typical multitasking setup, your program will act like multiple pieces of work are happening at the same time. Below is a flowchart utilizing reliable timers:

Flowchart

Some quick points about the above image:

  • The main task (or thread) is in some kind of loop doing work. Part of the work is “setting” a timer to go off. 
  • For clarification, assume the main task only starts the reliable timer if it is not already running
  • The main loop needs a way to exit, so assume that the user taps a key to break out of the loop.

Code Sample

Below is an example of code showing a complete program demonstrating the use of a reliable timer:

using System;
using System.Thhreading;

namespace MultitaskingTimers
{
	internal class Program
	{
		static int idx2 = 1;

		static void Main(string[] args)
		{
			int idx = 1;
			System.Threading.Timer myTimer = new Timer(Program.timerCallback, null, 0, 3000);

			while(true)
			{
				Console.WriteLine($"This is a line of text number {idx}");
				if(Console.KeyAvailable)
				{
					Environment.Exit(1);
				}
				Thread.Sleep(500);
				++idx;
			}
		}

		public static void timerCallback(Object o)
		{
			Console.WriteLine($"-- Output From Timer: {idx2}");
			++idx2;
		}
	}
}

The heart of this snippet it the definition of “myTimer”. We made the callback routine, timerCallback, a static method so that it can be called by using Program.timerCallback while invoking the timer’s callback. The instantiation of myTimer simple tells the system that there is a new Timer (System.Threading.Timer) which starts right away, and is triggered in 3000 milliseconds, or 3 seconds. The callback is the Program.timerCallback method which is passed a null parameter. The main program is an infinite loop which displays a console message every half-second. The loop exits when the user presses any key as shown by the Console.KeyAvailable test. Once a key is pressed, the program will end.

Because this program is meant to be a console program (i.e. runs in a command prompt window), all the output is sent to that window. A typical output from the above program would be:

Multitasking continued…

The next article in this series on multitasking introduces the ThreadPool.