Task and Task<T> represents a multithreaded task. It has many options to use. In this post, let’s focus on how to start a task run it.
You might have used “System.Threading.Thread” class without big troubles. I think the design of the “Thread” class is very traditional. If you have worked with multithreaded application for a while, you do not have any problems to understand how the “Thread” class works. But, admittedly, it is somehow technical and not intuitive, which makes the code error-prone.
Data Parallelism is one part of the “Task Parallel Library (TPL)”. You can iterate over a collection of data and perform some tasks for each item in a parallel fashion.
In .Net Framework 4 (C# 4), a set of types are added to the “System.Threading.Tasks” namespace. Collectively speaking, they are referred to as the “Task Parallel Library“, or TPL.
By default, delegates work synchronously. But you can use them asynchronously too. You do not even need to work with any types of “System.Threading” namespace.
The same technique can be applied to handle exceptions in a thread. You can just use a try/catch block.
But what if an unhandled exception is thrown from a thread? How can you handle it in the main thread? And what will happen?
Creating and destroying a thread can be an expensive operation. For better performance, you can make use of a thread pool. You can queue the task to the pool and the runtime will figure out how to create or reuse a thread in the pool.
Suppose you have an application to display the stock index. Rather than relying on the “refresh” button, you might want to refresh itself in a specific time interval. “System.Threading.Timer” can be used for this scenario.