views:

96

answers:

4

I am doing a multi-threaded application in C# and need to pass some parameters to a thread.

Attempting to use the ParameterizedThreadStart class so that I can pass a class variable (which contains all the parameters I want to pass). However, the class seems to be unrecognised (there is a red line underneath it in the source code) and on compilation I got a "The type or namespace name ParameterizedThreadStart could not be found (are you missing a using directive or an assembly reference?)".

I am using the following libraries from the framework: using System; using System.Collections; using System.Threading;

Am I doing anything wrong? I am using VS 2003 (7.1.6030) and .NET Framework 1.1.

Thank you.

+3  A: 

The ParameterizedThreadStart delegate was added in framework 2.0.

Instead of passing an object to the thread, you can start the thread using a method in the object, then the thread has access to the members of the object.

Example:

public class ThreadExample {

  public int A, B;

  public void Work() {
    A += B;
  }

}

ThreadExample thread = new ThreadExample();
thread.A = 1;
thread.B = 2;
new ThreadStart(thread.Work).Invoke();
Guffa
Thank you very much.
Andy
+1  A: 

requires .net 2.0, and it's a delegate, not a class.

John Knoeller
+3  A: 

The old way of doing this is to write a class to represent the state, and put the method there:

class MyState {
    private int foo;
    private string bar;
    public MyState(int foo, string bar) {
        this.foo = foo;
        this.bar = bar;
    }
    public void TheMethod() {...}
}
...
MyState obj = new MyState(123,"abc");
ThreadStart ts = new ThreadStart(obj.TheMethod);
Marc Gravell
Yes, this is what I ended up doing. I bundled all the variables I am interested in into a class and called a class method. Thank you.
Andy
+1  A: 

That ParameterizedThreadStart type not exists before .net framework 2.0, but you can accomplish the same goal (pass parameters to thread) creating a simple class and using good old ThreadStart delegate, like the following:

class ParamHolder
{
    private object data;

    public ParamHolder(object data) // better yet using the parameter(s) type
    {
        this.data = data;
    }

    public void DoWork()
    {
        // use data
        // do work
    }
}

and the use will be:

...
object param = 10; // assign some value
Thread thread = new Thread(new ThreadStart(new ParamHolder(param).DoWork));
thread.Start();
...
Alex LE