How to pass data to the thread?

Now, I want to pass some data to the thread when I start the thread. The Thread.Start() method has an overloaded method which accepts a object as a parameter. The one difference is, you will not use the ThreadStart delegate instead you will use the ParameterizedThreadStart. Fortunately .net simplifies the syntax much better way. Lets take a simple example. In this sample, you are creating the thread object and passing the instance method name.


namespace My_Samples
{
    using System;
    using System.Threading;

    public class MyClass
    {
        public void MyMethod(object data)
        {
            Console.WriteLine(data.ToString());
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyClass obj = new MyClass();
            Thread thread = new Thread(obj.MyMethod);
            thread.Start("Hello world");
            Console.WriteLine("Main method is completed...");
            Console.ReadLine();
        }
    }
}

No comments:

Post a Comment