Search this blog

You can search for all the topics in our blog using our google custom search now.

Search the blog


Sunday, June 20, 2010

Passing data to threads C# example

Passing data to Threads:
To pass data to threads, you need to store the data to variables of class when you call constructor.First in your class create a constructor with parameters whose values will be needed by threads.
For example:
class employee
//Class Variables
        public string name;
        public string designation;
        public string department;
        public string salary;

//My employee constructor
public Employee()
           name = "Sameer";
            designation = "Programmer";
            department = "IT";
            salary = "3000";


Now the above class has 4 variables whose values can be passed to any thread like this:
Am going to run a thread on below method, please see the definition

 public void displayname()
            Console.WriteLine("Name of the employee is : "+ name);

Now am going to create the thread as follows:
//Create a thread on displayname method
Thread t1 = new Thread(new ThreadStart(displayname));
//Start the thread as follows

If you check carefully, i haven't passed any parameters to method displayname. The only way to pass values to threads is by using public variables, the way its used in this example.

Please dont confuse yourself alot with this example. Start creating your own class and method. Passing values to thread should be piece of a cake.

Am going to post a detailed post on passing and retrieving values from threads in the next post. If you have any doubts on this, get back to me.

Sameer Shaik

Check out the video on this post:

No comments:

Post a Comment