Chapter 2 - Threading Classes
CoderSource.net
Chapter 2 - Threading Classes - Article by muskad202
Level: BeginnerType: Article
Rating: Page: 3 of 3

Date: 3/24/2006 12:00:00 AM

Environment: .Net 2.0, Windows

The ParameterizedThreadStart Delegate:

What if you want to pass a parameter to the function which you want to execute within your new thread? In that case, you cannot use the ThreadStart delegate.

You need to use the ParameterizedThreadStart delegate, as shown below:

    class Program

    {

        static void Main(string[] args)

        {

            Thread newThread = new Thread(new ParameterizedThreadStart(OtherFunction));

            newThread.Start("Hello");

            Console.WriteLine("Main thread going off to sleep");

            Thread.Sleep(1000);

            Console.WriteLine("Main thread has woken up. Returning"); 

        }

        static void OtherFunction(object param)

        {

            Console.WriteLine("Parameter passed to OtherFunction : " + param.ToString());

            for (int i = 1; i <= 10; i++)

            {

                Console.WriteLine("Inside the new thread. Current iteration = " + i);

                Thread.Sleep(100);

            }

        }

    }

Since the parameter is of type object, you can pretty much pass in anything you want. If you want to pass in multiple parameters, you can encapsulate them within an instance of another class you create, and then pass in that instance to the function, as shown below:

    class Person

    {

        public String Name;

        public int Age;

    }

    class Program

    {

        static void Main(string[] args)

        {

            Thread newThread = new Thread(new ParameterizedThreadStart(OtherFunction));

            Person p = new Person();

            p.Name = "Mustansir";

            p.Age = 22;

            newThread.Start(p);

         }

        static void OtherFunction(object param)

        {

            Person p = (Person)param;

            Console.WriteLine("Person information obtained : " + p.Name);

            Console.WriteLine("Person's Age : " + p.Age);

        }

    }

 


Attachments

Project Files C# Threading Samples

1 2 3

You Can Rate this Article, if you are Logged In      
 

More Links from CoderSource.net:

 
Refer to a Friend:

Your Details:

Name:     e-mail:

Friend Details:

Name:    e-mail:    


MENU
Home
MFC 
C++
.Net
WIN32
Programming
Forum
My Articles
Add to Google
Add to My Yahoo!
Welcome to Codersource.Net Login | Register | Faq  

SEARCH
Google
 

NOTES:


Thanks for visiting our CoderSource.net. This site will be improved with more articles. Interested visitors can also submit their articles through the Submit Article link.Your article will also be published after due consideration by the editor. 

© Copyright 2003. All rights on content reserved by CoderSource.net. Contact    About Us