Search Forum
(53671 Postings)
Search Site/Articles

Archived Articles
712 Articles

C# Books
C# Consultants
What Is C#?
Download Compiler
Code Archive
Archived Articles
Advertise
Contribute
C# Jobs
Beginners Tutorial
C# Contractors
C# Consulting
Links
C# Manual
Contact Us
Legal

GoDiagram for .NET from Northwoods Software www.nwoods.com


 
Printable Version

Recipe To Implement Threads Quick and Easy in C#
By Erlend Larsen

I'm pretty new to C#, but have already found out how easy multithreading is in this tailored language. I've used Visual C# .NET to come out with the recipe below. It's kind of a reference to remember the important points of creating a thread which can 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 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 
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. Now we'll change 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; 
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