Task.Run vs. Thread.Start?

I have a program which shuffles messages from a source to a queue.

Then it has another background thread running an endless loop which waits for a message to be added to the queue, then pulls that message from the queue and moves it to somewhere else.

Should that background thread be started using Task.Run() or Thread.Start()?

I don't really know how busy that background thread will be. It might be waiting most of the time for a new message to come; or messages might be coming so fast it doesn't have much time to wait.

This background thread will be running for quite a long time, as long as the user has that window open.

(Perhaps there's a third option I haven't thought of?)
deleydAsked:
Who is Participating?
 
Dirk StraussConnect With a Mentor Senior Full Stack DeveloperCommented:
Have a look at the explanation on C# Corner:


When we execute things on multiple threads, it’s not guaranteed that the threads are separated across multiple processors.

Task is a lightweight object for managing a parallelizable unit of work. It can be used whenever you want to execute something in parallel. Parallel means the work is spread across multiple processors to maximize computational speed. Tasks are tuned for leveraging multicores processors.

Task provides following powerful features over thread.
1. If system has multiple tasks then it make use of the CLR thread pool internally, and so do not have the overhead associated with creating a dedicated thread using the Thread. Also reduce the context switching time among multiple threads.
2. Task can return a result. There is no direct mechanism to return the result from thread.
3. Wait on a set of tasks, without a signaling construct.
4. We can chain tasks together to execute one after the other.
5. Establish a parent/child relationship when one task is started from another task.
6. Child task exception can propagate to parent task.
7. Task support cancellation through the use of cancellation tokens.
8. Asynchronous implementation is easy in task, using’ async’ and ‘await’ keywords.

Personally, I would use async and await. Have a look at Asynchronous Programming Succinctly which is a free eBook.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.