Search code examples
c#multithreadingobjectasynchronousparameterized

why does ParameterizedThreadStart work without getting any parameter?


I have a simple program which starts a thread. As an argument to the thread I pass a ParameterizedThreadStart delegate. Till here all good. Now When I start the thread, I need to pass it a required object, but suprisingly it all works well without giving it any object! How come?

class Program
{
    static void Main(string[] args)
   {
        Thread thread = new Thread(new ParameterizedThreadStart(F1));
        thread.Start();  //Why does it work with out passing any argument?
        Console.ReadLine();
    }

    public static void F1(object obj)
    {
        Console.WriteLine("Hello");
    }
}

The program prints Hello, and I expected to get an error.


Solution

  • You need to call the Thread.Start overload that takes a paramete: Eg:

    thread.Start("Hello world");
    

    The Start method you are calling will cause null to be passed to the thread function:

    If this overload is used with a thread created using a ParameterizedThreadStart delegate, null is passed to the method executed by the thread.