Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Tasks created as background threads?

Tags:

c#-4.0

I'm just wondering whether the new Task class in dot.net 4 is creating a background or foreground thread ?

Normally I'd set "IsBackground" on a Thread, but there's no such attribute on a Task.

I've not been able to find any documentation of this on MSDN :-(

like image 958
Steffen Avatar asked Mar 06 '11 08:03

Steffen


People also ask

Are tasks same as threads?

Differences Between Task And Thread The Thread class is used for creating and manipulating a thread in Windows. A Task represents some asynchronous operation and is part of the Task Parallel Library, a set of APIs for running tasks asynchronously and in parallel. The task can return a result.

What are background threads?

In programming, a background thread is a thread that runs behind the scenes, while the foreground thread continues to run. For instance, a background thread may perform calculations on user input while the user is entering information using a foreground thread.

What are foreground and background threads?

Background threads are identical to foreground threads with one exception: a background thread does not keep the managed execution environment running. Once all foreground threads have been stopped in a managed process (where the .exe file is a managed assembly), the system stops all background threads and shuts down.


2 Answers

Shouldn't be tough to verify:

class Program {     static void Main()     {         Task             .Factory             .StartNew(() => Console.WriteLine(Thread.CurrentThread.IsBackground))             .Wait();     } } 

And the answer is ...

ǝnɹʇ

like image 123
Darin Dimitrov Avatar answered Oct 11 '22 07:10

Darin Dimitrov


If you are starting a Task<T> using Task.Run(), then yes.

If you are using async and await, then no. Excerpt from here:

"The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active. You can use Task.Run to move CPU-bound work to a background thread, but a background thread doesn't help with a process that's just waiting for results to become available."

like image 44
Steztric Avatar answered Oct 11 '22 07:10

Steztric