Gun
Gun

Reputation: 1411

How to pass a method to Thread constructor?

How can I pass a Method2 to thread as shown in below if i write code as shown in below it shows an error Error

The best overloaded method match for 'System.Threading.Thread.Thread(System.Threading.ThreadStart)' has some invalid arguments

   class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Main Thread : ");           
            Thread obj = new Thread(Method2);
            obj.Start();                   
            Console.ReadLine();
        }       
        private static int Method2(int a)
        {
            return a;
        }
    }

When i use the following code it works

Thread obj = new Thread(() => Method2(1));

But why it's not working when i pass delegate object

delegate int del(int i);

del d = Method2;

Thread obj = new Thread(d);

What is the difference between above 2 , in 1st case i used Lambda expression in second case directly passed delegate object is there any thing else?

Upvotes: 0

Views: 1248

Answers (2)

Despertar
Despertar

Reputation: 22392

The Thread constuctor takes two types of delegates, ThreadStart and ParameterizedThreadStart. To see what type of method these delegates accept you can create it and the constructor will show you, so for example,

var parameterMethod = new ParameterizedThreadStart(...

If you type the above you will see the delegate takes a function with one object as the parameter and returns void.

void (object) target

This is why your Method that takes an int will not work because the signature does not match the delegate target signature. When you wrap it in a lambada, you are actually passing in a method that takes no parameters and returns void, so the Method2 signature is not even looked at. Wrapping method calls with a lambada like this can be very useful for getting the signature to match.

delegate void del(object obj);
del d = () => Method2(1);
Thread obj = new Thread(d);

There is an infinite number of possible method signatures so Threads and Tasks keep it simple and say if you want to pass something, pass a single object. Since all types derive from object, this lets you pass in anything you want, then cast it later.

Upvotes: 1

Krzysztof Cieslinski
Krzysztof Cieslinski

Reputation: 924

Try this:

Thread obj = new Thread(() => Method2(some_int_value));

Upvotes: 1

Related Questions