Recipe To Implement Threads Quick and Easy in C#


I'm pretty new to C#, but have already foundout how easy multithreading is in this tailored language. I've usedVisual C# .NET to come out with the recipe below. It's kind of areference to remember the important points of creating a thread whichcan update the GUI on its own.

You need:

- One Form file for user interface
- One Component class file added from menu: Project-Add Component.

1. Declare an instance of the Component class(Teller) in the Form class and create the object in the constructor ofthe 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

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

private void UpdateLabel(int Label, int integer)
{
lblTeller.Text = integer.ToString();
lblTeller2.Text = Label.ToString();
}

3. 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 is the function the thread will work through.
Thread thread = new Thread(new ThreadStart(Teller1.Counter));
thread.Start();
}

4. That was all changes to the Form file. Nowwe'll change the Component file. In the Component class we declare adelegate and an event. The event is an instance of the delegate. Thedelegate must have the exact same parameters as the function in theForm class to update/edit controls from threads.

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

5. Finally, all we need is the code for the thread.

public void Counter()
{
// Write something else to do here.
for (int i=0; i < 100000) Delegerer(1, i); // Uses UpdateLabel in Form class
}

6. Build it and run it. Voila

Related Articles :

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!