Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new thread with method with parameter [duplicate]

Tags:

I am trying to create new thread and pass a method with parameter,but errors out.

Thread t = new Thread(myMethod);
t.Start(myGrid);

public void myMethod(UltraGrid myGrid)
{
}

---------errors------------

Error: CS1502 - line 92 (164) - The best overloaded method match for 'System.Threading.Thread.Thread(System.Threading.ThreadStart)' has some invalid arguments

Error: CS1503 - line 92 (164) - Argument '1': cannot convert from 'method group' to 'System.Threading.ThreadStart'

like image 236
Lio Lou Avatar asked Feb 13 '13 13:02

Lio Lou


People also ask

How to create Parameterized thread in C#?

C# | Thread(ParameterizedThreadStart) Constructor It defined a delegate which allows an object to pass to the thread when the thread starts. This constructor gives ArgumentNullException if the parameter of this constructor is null. Syntax: public Thread(ParameterizedThreadStart start);

Which delegate is required to start a thread with one parameter?

The ParameterizedThreadStart delegate supports only a single parameter.

Can we pass parameter in thread?

The first way we can send a parameter to a thread is simply providing it to our Runnable or Callable in their constructor.


1 Answers

A more convenient way to pass parameters to method is using lambda expressions or anonymous methods, why because you can pass the method with the number of parameters it needs. ParameterizedThreadStart is limited to methods with only ONE parameter.

Thread t = new Thread(()=>myMethod(myGrid));
t.Start();

public void myMethod(UltraGrid myGrid)
{
}

if you had a method like

public void myMethod(UltraGrid myGrid, string s)
{
}

Thread t = new Thread(()=>myMethod(myGrid, "abc"));
t.Start();

http://www.albahari.com/threading/#_Passing_Data_to_a_Thread

Thats a great book to read!

like image 166
Igoy Avatar answered Oct 09 '22 10:10

Igoy