views:

76

answers:

3

How can I do this in c#? I have GUI and worker threads and I have to pass the array or be able to access the array from worker array?!

Thread t = new Thread (delegate() { DoWork (double[,] data); });
t.Start();


static void DoWork (double[,] data) { do some work...; }
+2  A: 

Use a parameterised thread delegate (ParameterisedThreadStart):

Thread t = new Thread(o =>
  {
    double[,] data = (double[,])o;
    DoWork(data);
  });

t.Start(myData);

EDIT: or as Paul suggests in comments, capture myData via a closure:

Thread t = new Thread(() => DoWork(myData));
t.Start();
itowlson
How is this better that just passing in a method (to ThreadStart ) to a class that contains the data?
Paul
Good point, if he only ever wants to call it on the myData local, capturing the data in a closure would also work: Thread t = new Thread(() => DoWork(myData));
itowlson
+1  A: 

All thread delegates accept an object. Pass the array and then cast in the worker:

double[,] myarray = ...;
ThreadPool.QueueUserWorkItem(state=>{
  double[,] arrayArg = (double[,])state;
  DoWork(arrayArg);
}, myarray);

ThreadStart has similar argument. Make sure you do no touch the array in UI thread while is under the worker control...

Remus Rusanu
Thank you guys all answers were good!!!
DLK
+1  A: 

From MSDN:

class Test
{
    static void Main() 
    {
        Work threadWork = new Work(yourdata);
        Thread newThread = 
            new Thread(new ThreadStart(threadWork.DoWork));
        newThread.Start();
    }
}

class Work 
{
    private double[,] myData;
    public Work(double[,] data) {
        myData = data;
    }

    public void DoWork() { /* use myData */ }
}
Pablo Santa Cruz