Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Cheers!

like image 622
8bitcat Avatar asked May 19 '12 22:05

8bitcat


1 Answers

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)

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()"

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

Best to read through : This MSDN Article

like image 152
GHz Avatar answered Oct 04 '22 03:10

GHz