This program creates a Thread
object and uses it to run a method in a separate thread. The method is defined in a class called ThreadingClass
, which has a DoStuff
method and a Stop
method. The DoStuff
method prints a message to the console and then waits for one second before printing the message again. The Stop
method sets a flag that causes the DoStuff
method to exit its loop and end.
The Main
method creates an instance of the ThreadingClass
class and then creates a Thread
object that will run the DoStuff
method. It starts the thread using the Start
method, and then waits for the user to press a key before calling the Stop
method to stop the thread. Finally, it calls the Join
method to wait for the thread to finish before ending the program.
While the program is running, the DoStuff
method will run in a separate thread and print its message repeatedly until the Stop
method is called. When the user presses a key, the Stop
method will be called, causing the DoStuff
method to exit its loop and end. The Join
method will then wait for the thread to finish before the program ends.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
using System; using System.Threading.Tasks; using System.Threading; class Program { static void Main(string[] args) { ThreadingClass th = new ThreadingClass(); Thread thread1 = new Thread(th.DoStuff); thread1.Start(); Console.WriteLine("Press any key to exit!!!"); Console.ReadKey(); th.Stop(); thread1.Join(); } } public class ThreadingClass { private bool flag = false; public void DoStuff() { while (!flag) { Console.WriteLine(" Thread is Still Working"); Thread.Sleep(1000); } } public void Stop() { flag = true; } } |