Creating new thread with method with parameter [duplicate]

一曲冷凌霜 提交于 2020-08-19 02:53:06

问题


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'


回答1:


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!




回答2:


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.




回答3:


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


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


来源:https://stackoverflow.com/questions/14854878/creating-new-thread-with-method-with-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!