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 argumentsError: CS1503 - line 92 (164) - Argument '1': cannot convert from 'method group' to '
System.Threading.ThreadStart
'
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);
The ParameterizedThreadStart delegate supports only a single parameter.
The first way we can send a parameter to a thread is simply providing it to our Runnable or Callable in their constructor.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With