Created
October 4, 2017 14:42
-
-
Save hulefei/a7186c85cb01c2fb53674d84948f81d4 to your computer and use it in GitHub Desktop.
stop the thread of C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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