开发者

C# ParameterizedThreadStart not supported in Visual Studio 2003?

开发者 https://www.devze.com 2022-12-17 18:16 出处:网络
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 al

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.


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


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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消