Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we pass any method except void in thread?

I am working on a thread. I have a method:

private int Calculate(int number);
can I used this method in a thread ?
Thread t = new Thread(new ThreadStart(Calculate));

We can't do that as ThreadStart() only accept void method. So, Is there any way to handle it using thread ? Also, If Calculate is void method, how can i pass argument in

thread t = new Thread(new ThreadStart(Calculate));
like image 843
Sanz Bajracharya Avatar asked Sep 12 '26 11:09

Sanz Bajracharya


2 Answers

You can use lambdas and the compiler will infer its type:

Thread t = new Thread(() => Calculate(number));
like image 167
Lucas Avatar answered Sep 15 '26 01:09

Lucas


You can use ParameterizedThreadStart and change the int type parameter to object and cast it back to int.

private int Calculate(object number)
{
   int num = Convert.ToInt32(number);
}
like image 34
Adil Avatar answered Sep 15 '26 02:09

Adil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!