简体   繁体   English

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

[英]C# Threading - How to start and stop a thread

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!干杯!

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 文章

Thread th = new Thread(function1);
th.Start();
th.Abort();

void function1(){
//code here
}

Use a static AutoResetEvent in your spawned threads to call back to the main thread using the Set() method.在您生成的线程中使用静态 AutoResetEvent 以使用 Set() 方法回调主线程。 This guy has a fairly good demo in SO on how to use it.这家伙在 SO 中有一个相当不错的演示,说明如何使用它。

AutoResetEvent clarification AutoResetEvent 说明

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

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