C# 线程 - 如何启动和停止线程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10669181/
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
C# Threading - How to start and stop a thread
提问by 8bitcat
Can anyone give me a headstart on the topic of threading? I think I know how to do a few things but I need to know how to do the following:
谁能给我一个关于线程主题的先机?我想我知道如何做一些事情,但我需要知道如何做以下事情:
Setup a main thread that will stay active until I signal it to stop(in case you wonder, it will terminate when data is received). Then i want a second thread to start which will capture data from a textbox and should quit when I signal it to that of which occurs when the user presses the enter key.
设置一个主线程,该线程将一直保持活动状态,直到我发出停止信号为止(如果您想知道,它会在收到数据时终止)。然后我希望启动第二个线程,该线程将从文本框中捕获数据,并在我向用户按下 Enter 键时发出信号时退出。
Cheers!
干杯!
采纳答案by GHz
This is how I do it...
我就是这样做的...
public class ThreadA {
public ThreadA(object[] args) {
...
}
public void Run() {
while (true) {
Thread.sleep(1000); // wait 1 second for something to happen.
doStuff();
if(conditionToExitReceived) // what im waiting for...
break;
}
//perform cleanup if there is any...
}
}
Then to run this in its own thread... ( I do it this way because I also want to send args to the thread)
然后在它自己的线程中运行它......(我这样做是因为我也想将 args 发送到线程)
private void FireThread(){
Thread thread = new Thread(new ThreadStart(this.startThread));
thread.start();
}
private void (startThread){
new ThreadA(args).Run();
}
The thread is created by calling "FireThread()"
线程是通过调用“FireThread()”创建的
The newly created thread will run until its condition to stop is met, then it dies...
新创建的线程将运行,直到满足其停止条件,然后它就会死亡......
You can signal the "main" with delegates, to tell it when the thread has died.. so you can then start the second one...
你可以用委托给“main”发信号,告诉它线程什么时候死了..这样你就可以开始第二个......
Best to read through : This MSDN Article
最好通读:这篇 MSDN 文章
回答by Ali Tarhini
Thread th = new Thread(function1);
th.Start();
th.Abort();
void function1(){
//code here
}
回答by MrWuf
Use a static AutoResetEvent in your spawned threads to call back to the main thread using the Set() method. This guy has a fairly good demo in SO on how to use it.
在您生成的线程中使用静态 AutoResetEvent 以使用 Set() 方法回调主线程。这家伙在 SO 中有一个相当不错的演示,说明如何使用它。

