Creating New Thread with Method with Parameter [Duplicate]

Creating New Thread with Method with Parameter [Duplicate]

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'

2

3 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();

Thats a great book to read!

1

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.

1
    public void myMethod(object myGrid)
    {
        var typedParam = (UltraGrid)myGrid;
        //...
    }


    Thread t = new Thread(new ParameterizedThreadStart(myMethod));
    t.Start(myGrid);
1
James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.