Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters to thread by reference in c#?

I have to pass multiple parameters to a thread. I have wrapped them into a class object. In which one variable (double array) i want pass it as reference (I am expecting the result in this variable). How does it possible?

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);
like image 892
sdev Avatar asked Jan 18 '12 15:01

sdev


People also ask

Can we pass parameters by reference in C?

Passing by by reference refers to a method of passing the address of an argument in the calling function to a corresponding parameter in the called function. In C, the corresponding parameter in the called function must be declared as a pointer type.

How do you pass parameters by reference?

Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in. The following example shows how arguments are passed by reference.

How do you pass multiple arguments to a thread?

Passing Multiple Arguments to Threads. When passing multiple arguments to a child thread, the standard approach is to group the arguments within a struct declaration, as shown in Code Listing 6.9. The address of the struct instance gets passed as the arg to pthread_create() .


2 Answers

Description

There are many solutions. One is, you can use ParameterizedThreadStart for that.

Sample

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

More Information

  • MSDN - ParameterizedThreadStart Delegate
like image 165
dknaack Avatar answered Oct 21 '22 04:10

dknaack


You could also just pass the param variable when you declare the thread:

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

Check out Joseph Albahari's free e-book on threading here.

I like this approach since you don't need to deal with other objects -- just create a lambda in your Thread constructor and you're off to the races.

Hope this helps!

like image 24
David Hoerster Avatar answered Oct 21 '22 03:10

David Hoerster