How to Stop a Thread
Unfortunately there may not be a better option. It really depends on your specific scenario. But there are several options. First, you can use your own communication mechanism to tell the ThreadStart method to finish. Alternatively the Thread class has in-built support for instructing the thread to stop. The two principle methods are Thread.Interrupt() and Thread.Abort() .
The former will cause a ThreadInterruptedException to be thrown on the thread when it next goes into a WaitJoinSleep state. In other words, Thread.Interrupt is a polite way of asking the thread to stop when it is no longer doing any useful work. The advantage here is that it is simple and you do not have to focus on sprinkling your code with anything really.
The idea is to stop the thread gracefully at safe points. That is the crux of the reason why Thread.Abort is not good; because it is not guaranteed to occur at safe points. Thread.Abort() throws a ThreadAbortException regardless of what the thread is doing. Furthermore, the ThreadAbortException cannot normally be caught (though the ThreadStart's finally method will be executed). Thread.Abort() is a heavy-handed mechanism which should not normally be required.
Thread in computer science means a sequence of execution instructions that can run independently , that is a single flow of execution in a process. Thread is like a process, at least one thread exists within each process. Single Thread (normal programs) in computer science means that only one task can execute and at the same time the other tasks have to wait for the completion of the current task like in a queue. Single thread resulted in systems idle time and application performance.
More on.... Understanding Threading in .NET Framework
- C# Frequently Asked Questions - 1
- C# Frequently Asked Questions - 2
- C# Frequently Asked Questions - 3
- Difference between a Debug and Release build
- Difference between normal DLL and .Net DLL
- What is an Interface in C#
- Difference between Abstract Class and Interface
- Difference between a thread and a process
- What is .Net Delegates
- Differences between a control and a component
- Differences between Stack and Heap
- What is .Net Reflection
- Globalization and Localization
- What is .Net serialization
- Difference between web service and .net remoting
- Difference between managed and unmanaged code
- Difference between Shallow copy and Deep copy
- Use of System.Environment Class
- What is the difference between private and shared assembly?
- Does the .NET have in-built support for serialization?
- Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
- Why is XmlSerializer so slow?
- How many types of Jit Compilers?