I see a lot of people in blog posts and here on SO either avoiding or advising against the usage of the Thread
class in recent versions of C# (and I mean of course 4.0+, with the addition of Task
& friends). Even before, there were debates about the fact that a plain old thread's functionality can be replaced in many cases by the ThreadPool
class.
Also, other specialized mechanisms are further rendering the Thread
class less appealing, such as Timer
s replacing the ugly Thread
+ Sleep
combo, while for GUIs we have BackgroundWorker
, etc.
Still, the Thread
seems to remain a very familiar concept for some people (myself included), people that, when confronted with a task that involves some kind of parallel execution, jump directly to using the good old Thread
class. I've been wondering lately if it's time to amend my ways.
So my question is, are there any cases when it's necessary or useful to use a plain old Thread
object instead of one of the above constructs?
Thread Class Constructors This constructor will createa thread from the runnable object. This constructor will create a thread with the name as per argument passed.
Once a thread in the thread pool completes its task, it's returned to a queue of waiting threads. From this moment it can be reused. This reuse enables applications to avoid the cost of creating a new thread for each task. There is only one thread pool per process.
To lock a static method, use a private static object, and for a private object, lock the instance method. When locking a class instance, this will work fine if it is exposed externally and used. Suppose I have written MythreadClass and locking this to implement a thread safety.
There are mainly Three ways to create a new thread: (1) By implementing Runnable interface in your class. (2) By extending Thread class. (3) By using inner class.
The Thread class cannot be made obsolete because obviously it is an implementation detail of all those other patterns you mention.
But that's not really your question; your question is
are there any cases when it's necessary or useful to use a plain old Thread object instead of one of the above constructs?
Sure. In precisely those cases where one of the higher-level constructs does not meet your needs.
My advice is that if you find yourself in a situation where existing higher-abstraction tools do not meet your needs, and you wish to implement a solution using threads, then you should identify the missing abstraction that you really need, and then implement that abstraction using threads, and then use the abstraction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With