Languages
[Edit]
EN

C#/.NET - stop thread

8 points
Created by:
Kate_C
2854

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
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.