C#线程 - 如何启动和停止一个线程

C#线程 - 如何启动和停止一个线程

问题描述:

谁能给我穿线的话题领先地位?我想我知道该怎么做了几件事情,但我需要知道如何做到以下几点:

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.

干杯!

这是我该怎么办呢?

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...
    }
}

然后在自己的线程运行这个...(我做这种方式,因为我也想送args设置为线程)

Then to run this in its own thread... ( I do it this way because I also want to send args to the thread)

private void FireThread(){
    Thread thread = new Thread(new ThreadStart(this.startThread));
    thread.start();
}
private void (startThread){
    new ThreadA(args).Run();
}



线程通过调用创建FireThread()

The thread is created by calling "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...

最好能通读:的这个MSDN文章