如何在线程c#之间传递参数(对象和字符串)?

时间:2017-05-16 16:51:21

标签: c# multithreading parameters parameter-passing


我有这段小代码。如何将参数(对象和字符串)传递给线程(在“th = new Thread(play);”行中)?
谢谢!

private Thread th = null;

private void Form1_KeyDown(object sender, KeyPressEventArgs e)
{
    [...]
    th = new Thread(play);
    th.Start();
}

private void play(object sender, string name)
{
    [...]
}

1 个答案:

答案 0 :(得分:0)

您需要更改play()方法的签名:

private void play(object data)
{
    object[] array = (object[])data;  // data is actually an array of objects

    object sender = array[0];
    string name = (string)array[1];
}

然后你只需要改变你开始线程的方式:

th.Start(new object[] { sender, "whatever name" });