Are Tasks created as background threads?
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 :-(
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ɹʇ
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."
It appears to run as a background thread.
See this thread:
Running multiple C# Task Async