C# 如何创建线程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/811224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a thread?
提问by Ivan Prodanov
The method below is what I want to be done in that thread:
下面的方法是我想在该线程中完成的:
public void Startup(int port,string path)
{
Run(path);
CRCCheck2();
CRCCheck1();
InitializeCodeCave((ushort)port);
}
I tried what I could find googling,but nothing worked
我尝试了我能找到的谷歌搜索,但没有任何效果
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);
}
Both don't compile,how to do that?
两者都不能编译,怎么办?
采纳答案by Mikko Rantanen
The following ways work.
以下方法有效。
// 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();
The Startup methods have following signature for these examples.
这些示例的 Startup 方法具有以下签名。
public void StartupA(object parameters);
public void StartupB(int port, string path);
回答by Greg D
The method that you want to run must be a ThreadStart
Delegate. Please consult the Thread
documentationon MSDN. Note that you can sort of create your two-parameter start with a closure. Something like:
您要运行的方法必须是ThreadStart
Delegate。请查阅MSDN 上的Thread
文档。请注意,您可以使用闭包创建双参数开头。就像是:
var t = new Thread(() => Startup(port, path));
Note that you may want to revisit your method accessibility. If I saw a class starting a thread on its own public method in this manner, I'd be a little surprised.
请注意,您可能希望重新访问您的方法可访问性。如果我看到一个类以这种方式在自己的公共方法上启动一个线程,我会有点惊讶。
回答by CSharpAtl
public class ThreadParameter
{
public int Port { get; set; }
public string Path { get; set; }
}
Thread t = new Thread(new ParameterizedThreadStart(Startup));
t.Start(new ThreadParameter() { Port = port, Path = path});
Create an object with the port and path objects and pass it to the Startup method.
使用端口和路径对象创建一个对象并将其传递给 Startup 方法。
回答by Nathan Ridley
Your example fails because Thread methods take either one or zero arguments. To create a thread without passing arguments, your code looks like this:
您的示例失败,因为 Thread 方法采用一个或零个参数。要在不传递参数的情况下创建线程,您的代码如下所示:
void Start()
{
// do stuff
}
void Test()
{
new Thread(new ThreadStart(Start)).Start();
}
If you want to pass data to the thread, you need to encapsulate your data into a single object, whether that is a custom class of your own design, or a dictionary object or something else. You then need to use the ParameterizedThreadStartdelegate, like so:
如果要将数据传递给线程,则需要将数据封装到单个对象中,无论是您自己设计的自定义类,还是字典对象或其他东西。然后您需要使用ParameterizedThreadStart委托,如下所示:
void Start(object data)
{
MyClass myData = (MyClass)myData;
// do stuff
}
void Test(MyClass data)
{
new Thread(new ParameterizedThreadStart(Start)).Start(data);
}
回答by anhoppe
UpdateThe currently suggested way to start a Task is simply using Task.Run()
更新当前建议的启动任务的方法是简单地使用 Task.Run()
Task.Run(() => foo());
Note that this method is described as the best way to start a task see here
请注意,此方法被描述为启动任务的最佳方式,请参见此处
Previous answer
上一个答案
I like the Task Factory from System.Threading.Tasks. You can do something like this:
我喜欢 System.Threading.Tasks 中的任务工厂。你可以这样做:
Task.Factory.StartNew(() =>
{
// Whatever code you want in your thread
});
Note that the task factory gives you additional convenience options like ContinueWith:
请注意,任务工厂为您提供了额外的便利选项,例如ContinueWith:
Task.Factory.StartNew(() => {}).ContinueWith((result) =>
{
// Whatever code should be executed after the newly started thread.
});
Also note that a task is a slightly different concept than threads. They nicely fit with the async/await keywords, see here.
另请注意,任务与线程的概念略有不同。它们非常适合 async/await 关键字,请参见此处。