Languages
[Edit]
EN

C#/.NET - stop thread

8 points
Created by:
Kate_C
19790

To stop thread in C#/.NET additional variable should be used.

bool looped = true;

Thread thread = new Thread(() =>
{
	Console.WriteLine("Started");

	for (int i = 1; looped; ++i)
	{
		Console.WriteLine("Iteration: " + i);
		Thread.Sleep(300);
	}

	Console.WriteLine("Stopping");
});

Console.WriteLine("Starting");

thread.Start();
Thread.Sleep(1000);

looped = false;
thread.Join();

Console.WriteLine("Stopped");

Where:

  • looped variable - keeps thread working
  • Thread.Join method - sleeps current code until executed thread will not finish working

Output:

Starting
Started
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Stopping
Stopped
Note: Stopping thread by Thread.Abort method is wrong practice. To solve problem looped variable is used. Read more here.

References

  1. Thread Class - Microsoft Docs
  2. Thread.Join method - Microsoft Docs

See also

  1. C#/.NET - create thread
  2. C#/.NET - join thread
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join