23

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'

Umar Abbas
  • 4,399
  • 1
  • 18
  • 23
Lio Lou
  • 263
  • 1
  • 3
  • 9

3 Answers3

78

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!

Igoy
  • 2,942
  • 22
  • 23
15

Change your thread initialization to:

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

And also the method to:

public void myMethod(object myGrid)
{
    var grid = (UltraGrid)myGrid;
}

To match the ParameterizedThreadStart delegate signature.

Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
gzaxx
  • 17,312
  • 2
  • 36
  • 54
  • 4
    There's no need to use `ParameterizedThreadStart` at all, since the appropriate delegate type can be inferred. So just changing the parameter `myGrid` to `object` is enough. – sloth Feb 13 '13 at 13:47
0
    public void myMethod(object myGrid)
    {
        var typedParam = (UltraGrid)myGrid;
        //...
    }


    Thread t = new Thread(new ParameterizedThreadStart(myMethod));
    t.Start(myGrid);
ken2k
  • 48,145
  • 10
  • 116
  • 176
  • This is neat, but what if myMethod is returning something? What changes should I do to the code? – PewK Oct 11 '14 at 14:15