EN
C#/.NET - stop thread
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 workingThread.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 byThread.Abort
method is wrong practice. To solve problemlooped
variable is used. Read more here.