Top community members
All Wiki Articles Create Wiki Article

Have you ever heard about encyclopedia for code?

What about: Wiki for Code project?

* because I've tried to share code and my solutions on different services and it was removed or I was unwelcomed
   - maybe it wasn't good place, but this one is.

if you think you have solution that can help someone, you are welcome to share this solution - Click here

C#/.NET - stop thread

0 contributions
8 points

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
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more