Timers Sample - Two Timers Working in Tandem

I have seen people getting confused with timers. As timers launch a new thread, the problem worsens if one has more than one of them on the same form. I am pleased to share the sample solution attached, with the community. The sample uses two timers and demonstrates how to tame them.

There are pictures of three faces (happy, neutral, and sad) on the form. The sample uses two timers- DisplayTimer to display each face one by one, and HideTimer to hide each face one by one. The timers keep doing their work until the user clicks the Exit button. The two timers besides working in their own thread, work mutually exclusive of each other. The code of the sample is well - commented and follows general naming convention.

Following are the points to note about the sample:

Constraints:

A timer always starts a new thread.

Business logic:

  1. Display the faces one by one.
  2. Unless all the faces are displayed completely, don't start hiding them.
  3. Hide the faces one by one.
  4. Unless all the faces are hidden, don't start displaying them again.
  5. Even if more faces (images) are added on the form later, we shouldn't need to change the code.

Optimization:

No controls are added on the form at run time. Therefore, the sample retrieves the index of each PictureBox in the controls collection, and stores it in a local array. Thus, we don't need to loop thru the Controls collection repeatedly.

How to read the Program

Display and Hide timers need to be mutually exclusive. The sample uses some form level permission variables to achieve this.

  1. Take look at the region "Form Level Variables" first.
  2. Then the Sub Form_Load().
  3. Then Sub Display_Tick(), and Sub Hide_Tick(). These are almost alike.
  4. There are some simple try Catch blocks in place.
  5. There is some cleaning code in the btnExit_click().