Recipe to Implement Threads Quick n Easy in C#


You need:

  1. One Form file for user interface, with one button (btnStart) and two labels (lblTeller1 & lblTeller2).

  2. One Component class file added from menu: Project-Add Component.

1. Enable threading in the program by adding this to the top of the Form file.

using System.Threading;

2. Declare an instance of the Component class (Teller) in the Form class and create the object in the constructor of the Form class.

private Teller Teller1; // Outside the constructor
Teller1 = new Teller(); // Inside the constructor
// Enables a function in Teller class to use UpdateLabel() through a delegate
// declared in Teller class.
Teller1.Delegerer += new Teller.DelegatEn(this.UpdateLabel);
// Inside the constructor 

3. Create a function in the Form class to update/edit controls from threads.

private void UpdateLabel(int Label, int integer)
{
switch(Label)
{
case 1:
lblTeller.Text = integer.ToString();
break;
case 2:
lblTeller2.Text = integer.ToString();
break;
case 3:
btnStart.Enabled =
true;
break;
}
}

4. Add function to deal with starting the thread, for instance by the click of a button.

private void btnStart_Click(object sender, System.EventArgs e)
{
btnStart.Enabled =
false;
// Teller1.Counter and Counter2 is the functions the two threads will work
// through.
Thread thread1 = new Thread(new ThreadStart(Teller1.Counter));
thread1.Start();
Thread thread2 =
new Thread(new ThreadStart(Teller1.Counter2));
thread2.Start();
}

5. That was the Form file. Now the Component file. In the Component class we declare a delegate and an event. The event is an instance of the delegate. The delegate must have the exact same parameters as the function in the Form class to update/edit controls from threads.

public delegate void DelegatEn(int Label, int integer);
public event DelegatEn Delegerer;

6. Finally, all we need is the code for the two threads.

public void Counter()
{
// Uses UpdateLabel in Form class
for (int i=0; i<100000; i++) Delegerer(1, i);
Delegerer(3, 0);
// Enable btnStart
}
public void Counter2()
{
for (int i=100000; i>0; i--) Delegerer(2, i);
}

7. Build it and run it. Voila!

Up Next
    Ebook Download
    View all
    Learn
    View all