如何在c#中通过引用将参数传递给线程?

时间:2012-01-18 15:04:13

标签: c# multithreading

我必须将多个参数传递给一个线程。我把它们包装成了一个类对象。我希望在其中传递一个变量(双数组)作为参考(我期望在此变量中得到结果)。怎么可能?

class param
{
   int offset = 0;
   double[] v = null;
}
param p = new param();
p.v = new double[100]; // I want to pass this(v) variable by reference
p.offset = 50;

....
thread1.Start(p);

4 个答案:

答案 0 :(得分:6)

描述

有很多解决方案。一个是,您可以使用ParameterizedThreadStart

示例

param p = new param();

// start the thread, and pass in your variable   
Thread th = new Thread(new ParameterizedThreadStart(MyThreadMethod));
th.Start(p);

public void MyThreadMethod(object o)
{
    // o is your param
    param pv = (param)o;
}

更多信息

答案 1 :(得分:3)

您也可以在声明线程时传递param变量:

static void Main()
{
  param p = new param();
  p.v = new double[100]; // I want to pass this(v) variable as reference
  p.offset = 50;
  Thread t = new Thread ( () => MyThreadMethod(p) );
  t.Start();
}

static void MyThreadMethod(param p) 
{
  //do something with p
  Console.WriteLine(p.v.Length);
  Console.WriteLine(p.offset);
}

查看Joseph Albahari关于线程here的免费电子书。

我喜欢这种方法,因为你不需要处理其他对象 - 只需在你的Thread构造函数中创建一个lambda,然后你即可参加比赛。

希望这有帮助!

答案 2 :(得分:0)

您将如何做到这一点:

    static void Main(string[] args)
    {
        int offset = 0;
        double[] v = null;

        //Put your values into a single object
        object o = new object[] { offset, v };

        Thread thread1 = new Thread(new ParameterizedThreadStart(myMethod));
        thread1.Start(o);

    }
    public static void myMethod(object sender)
    {
        //Do something
    }

答案 3 :(得分:0)

由于线程正在访问p的成员,p本身不需要通过引用传递。仅当线程使用p将新对象分配到p = new MyParams();时,您才需要将p作为参考传递。

相关问题