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

本文关键字:引用 参数传递 线程 | 更新日期: 2023-09-27 18:20:35

我必须将多个参数传递给一个线程。我已经将它们包装成一个类对象。在其中一个变量(双数组)中,我希望将其作为引用传递(我希望在该变量中得到结果)。这怎么可能?

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

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

描述

有很多解决方案。一个是,您可以使用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;
}

更多信息

  • MSDN-参数化线程启动委派

您也可以在声明线程时只传递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关于线程的免费电子书。

我喜欢这种方法,因为您不需要处理其他对象——只需在Thread构造函数中创建一个lambda,就可以开始比赛了。

希望这能有所帮助!

由于线程正在访问p的成员,因此p本身不需要通过引用传递。只有当线程用p = new MyParams();p分配了一个新对象时,才需要传递p作为引用。

以下是您的操作方法:

    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
    }

我尝试完整答案。。

public class abc
{
    public string ttt { get; set; }
    public string fff { get; set; }
    public int v { get; set; }
    public double[] d { get; set; }
}
public void MyThreadMethod2(ref string str, ref double[] dd)
{
    str = "777";
    dd[2] = 9.9;
}
public void MyThreadMethod(object o)
{
    // o is your param
    abc pv = (abc)o;
    pv.v = 1;
    string sss = pv.fff; #because you can't ref pv, so ref sss 
    double[] mmm = pv.d;
    MyThreadMethod2(ref sss, ref mmm);
    pv.fff = sss; # and change pv.fff
}

abc aaaa = new abc();
aaaa.fff = "666";
aaaa.ttt = "666";
aaaa.v = 0;
aaaa.d = new double[3];
aaaa.d[0] = 1.0;
aaaa.d[1] = 1.1;
aaaa.d[2] = 1.2;
Thread th = new Thread(new ParameterizedThreadStart(MyThreadMethod));
th.Start(aaaa);
THREAD_WAIT:;
            
if(aaaa.v == 0)
{
    MessageBox.Show(aaaa.fff);
    Thread.Sleep(1000);
    goto THREAD_WAIT;
}
else
{
    MessageBox.Show(aaaa.fff);
    MessageBox.Show(aaaa.d[2].ToString());
}