Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

stop a thread c#

/* Below is a basic thread.
 * Since Thread.Abort() is no longer supported, you can use the following
 * as a replacement.
 * First create a global bool variable, I named my "END" and set it to: false
 * When you want to kill/abort your thread, write: END = true;
 */

bool END = false;
Thread thread = new Thread(() =>
{
  int x = 1;
  Thread.CurrentThread.IsBackground = true;

  // this thread will print the elapsed seconds until the END variable is: true
  while (true)
  {
    if (END) return; // terminates the thread
  	Thread.Sleep(1000);
  	Console.Writeline($"{x} seconds have passed");
  }
}).Start();

// the thread will run until this line is read:
END = true;
 
PREVIOUS NEXT
Tagged: #stop #thread
ADD COMMENT
Topic
Name
1+3 =