Reputation: 1613
I've been programming in C++
for years and then moved to .NET
. Everything much easier to understand so far, but I still struggle with synchronization things (in theory).
I remember seeing here on Stackoverflow that running a Task
won't actually create a new thread! That got me really confused.
How does asynchronous tasks run in .NET
?
Can you explain why
var value = await Task<int>.Run(() => { return 10; } );
doesn't spawn a new thread? And what it does instead?
Also, what exactly does Dispatcher.BeginInvoke
on WPF
?
Upvotes: 2
Views: 616
Reputation: 171178
Tasks are run on TaskScheduler
s. A scheduler can do anything but the most common default scheduler uses the CLR thread-pool. Starting a task might start a new thread or reuse an existing one. It is not necessary to be able to tell the difference.
You can force a new thread to be started using TaskCreationOptions.LongRunning
.
await
has nothing to do with this at all. await
suspends execution of the current method until the awaited "thing" is completed. It never starts something, it only waits.
Note, that Task<int>.Run
should be Task.Run
. Those two expressions bind to the same method (Task.Run
) but the former one is misleading.
Dispatcher.BeginInvoke
has no relation to any of this. You can use this method to get an arbitrary delegate to be run on the WPF UI thread.
Upvotes: 4