如何创建一个线程?

Iva*_*nov 54 c# multithreading

下面的方法是我想在该线程中完成的:

public void Startup(int port,string path)
{
    Run(path);
    CRCCheck2();
    CRCCheck1();
    InitializeCodeCave((ushort)port);
}
Run Code Online (Sandbox Code Playgroud)

我试着用谷歌搜索,但没有任何效果

public void Test(int port,string path)
{
    Thread t = new Thread(Startup(port,path));
}

public void TestA(int port,string path)
{
    Thread t = new Thread(Startup);
    t.Start (port,path);
}
Run Code Online (Sandbox Code Playgroud)

两者都不编译,怎么办?

Mik*_*nen 75

以下方式有效.

// The old way of using ParameterizedThreadStart. This requires a
// method which takes ONE object as the parameter so you need to
// encapsulate the parameters inside one object.
Thread t = new Thread(new ParameterizedThreadStart(StartupA));
t.Start(new MyThreadParams(path, port));

// You can also use an anonymous delegate to do this.
Thread t2 = new Thread(delegate()
{
    StartupB(port, path);
});
t2.Start();

// Or lambda expressions if you are using C# 3.0
Thread t3 = new Thread(() => StartupB(port, path));
t3.Start();
Run Code Online (Sandbox Code Playgroud)

Startup方法对这些示例具有以下签名.

public void StartupA(object parameters);

public void StartupB(int port, string path);
Run Code Online (Sandbox Code Playgroud)


anh*_*ppe 15

我喜欢System.Threading.Tasks的Task Factory.你可以这样做:

Task.Run(() => foo());
Run Code Online (Sandbox Code Playgroud)

请注意,任务工厂为您提供了其他便利选项,如ContinueWith:

Task.Factory.StartNew(() => 
{
    // Whatever code you want in your thread
});
Run Code Online (Sandbox Code Playgroud)

还要注意,任务与线程略有不同.它们非常适合async/await关键字,请参见此处.


Gre*_*g D 8

要运行的方法必须是ThreadStartDelegate.请参阅MSDN上的Thread文档.请注意,您可以使用闭包创建双参数start.就像是:

var t = new Thread(() => Startup(port, path));
Run Code Online (Sandbox Code Playgroud)

请注意,您可能希望重新访问方法可访问性.如果我看到一个类以这种方式在自己的公共方法上开始一个线程,我会有点惊讶.


Nat*_*ley 5

您的示例失败,因为 Thread 方法采用一个或零个参数。要创建一个不传递参数的线程,您的代码如下所示:

void Start()
{
    // do stuff
}

void Test()
{
    new Thread(new ThreadStart(Start)).Start();
}
Run Code Online (Sandbox Code Playgroud)

如果要将数据传递到线程,则需要将数据封装到单个对象中,无论是您自己设计的自定义类,还是字典对象或其他对象。然后,您需要使用ParameterizedThreadStart委托,如下所示:

void Start(object data)
{
    MyClass myData = (MyClass)myData;
    // do stuff
}

void Test(MyClass data)
{
    new Thread(new ParameterizedThreadStart(Start)).Start(data);
}
Run Code Online (Sandbox Code Playgroud)