2

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?

Alexandre Severino
  • 1,563
  • 1
  • 16
  • 38
  • You _can_ create threads in .NET (just like using C++) and you _can_ force `Task`-s to run on a separate thread if that's what you need. Not an answer, just so you're aware (in case you aren't :) ). – xxbbcc May 19 '15 at 22:37
  • Tasks are executed on a thread pool. They may or may not need a new thread dedicated to them. If you really really want a new thread, you can use the `Thread` class. – zneak May 19 '15 at 22:37
  • Ok. But how do I get to know when a Task is run on a thread pool and when is not? And how do a **thread pool** works on .NET? – Alexandre Severino May 19 '15 at 22:38
  • @AlexandreSeverino http://stackoverflow.com/questions/230003/thread-vs-threadpool – xxbbcc May 19 '15 at 22:42

1 Answers1

4

Tasks are run on TaskSchedulers. 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.

usr
  • 168,620
  • 35
  • 240
  • 369
  • 1
    .Net and all those high level languages put everything "under the hood" and end up making everything so simple to use that it becomes complicated to understand "what actually happens on behind". Kind Regards. – Alexandre Severino May 19 '15 at 22:46
  • That is true. I sometimes find it easier to understand systems in terms of implementation details rather than looking at guarantees made only. – usr May 19 '15 at 22:47