Skip to content

Instantly share code, notes, and snippets.

@hulefei
Created October 4, 2017 14:42
Show Gist options
  • Save hulefei/a7186c85cb01c2fb53674d84948f81d4 to your computer and use it in GitHub Desktop.
Save hulefei/a7186c85cb01c2fb53674d84948f81d4 to your computer and use it in GitHub Desktop.
stop the thread of C#
class MyThreadClass
{
ManualResetEvent _stopEvent;
Thread _thread;
public MyThreadClass()
{
}
public void Start()
{
_stopEvent = new ManualResetEvent(false);
_thread = new Thread(new ThreadStart(ThreadFunction));
_thread.Start();
}
public void Stop()
{
_stopEvent.Set();
_thread.Join(); // block until thread completed
}
private void ThreadFunction()
{
int index = 0;
while (!_stopEvent.WaitOne(0))
{
Thread.Sleep(500);
Console.WriteLine("{0}", index);
++index;
}
}
}
class Program
{
static void Main(string[] args)
{
MyThreadClass example = new MyThreadClass();
example.Start();
Thread.Sleep(10000);
example.Stop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment