简体   繁体   English

Visual Studio 2003中不支持C#ParameterizedThreadStart?

[英]C# ParameterizedThreadStart not supported in Visual Studio 2003?

I am doing a multi-threaded application in C# and need to pass some parameters to a thread. 我在C#中做一个多线程应用程序,需要将一些参数传递给一个线程。

Attempting to use the ParameterizedThreadStart class so that I can pass a class variable (which contains all the parameters I want to pass). 试图使用ParameterizedThreadStart类,以便我可以传递一个类变量(包含我想传递的所有参数)。 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?)". 但是,这个类似乎无法识别(在源代码中它下面有一条红线)并且在编译时我得到了“无法找到类型或命名空间名称ParameterizedThreadStart(你是否缺少using指令或程序集引用? )”。

I am using the following libraries from the framework: using System; 我正在使用框架中的以下库:using System; using System.Collections; 使用System.Collections; using System.Threading; 使用System.Threading;

Am I doing anything wrong? 我做错了吗? I am using VS 2003 (7.1.6030) and .NET Framework 1.1. 我正在使用VS 2003(7.1.6030)和.NET Framework 1.1。

Thank you. 谢谢。

The ParameterizedThreadStart delegate was added in framework 2.0. ParameterizedThreadStart委托已添加到框架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();

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

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: 在.net framework 2.0之前,ParameterizedThreadStart类型不存在,但您可以完成相同的目标(将参数传递给线程)创建一个简单的类并使用旧的ThreadStart委托,如下所示:

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

需要.net 2.0,它是一个委托,而不是一个类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM