0

As the question says. I'd like to know if simply calling await in code has the potential to create a new thread.

Let's assume it's during a console app.

Alexander Trauzzi
  • 7,277
  • 13
  • 68
  • 112
  • 3
    It depends what you're awaiting. Read http://msmvps.com/blogs/jon_skeet/archive/2011/05/08/eduasync-part-1-introduction.aspx – SLaks Mar 10 '14 at 16:38
  • 2
    "await" is about asynchrony. Multiple threads are only *one* way to do asynchrony. – Peter Ritchie Mar 10 '14 at 16:41
  • Of course, I'm just inquiring as to the runtime's attitude towards receiving `Task` instances and whether it makes any decisions for me. – Alexander Trauzzi Mar 10 '14 at 16:42

1 Answers1

3

Microsoft's .NET 4.5 Task implementation will first try to invoke await-based continuations inline (i.e., on whatever thread completes the task). If it can't be executed inline (e.g., due to stack depth or use of a SynchronizationContext) the system thread pool is used instead. It won't explicitly create a new thread, though it might trigger the creation of a new thread in the pool.

See System.Threading.Tasks.AwaitTaskContinuation in the reference sources for details.

Note that this answer only applies to an awaited Task, and only on the Microsoft .NET 4.5 Framework. Also, if you are awaiting from a thread with a SynchronizationContext, and you are not using ConfigureAwait(false), then it would depend on the SynchronizationContext implementation. No new threads should be created for a WinForms, WPF, or Silverlight SynchronizationContext.

Mike Strobel
  • 25,075
  • 57
  • 69
  • Any insights when running on Mono? – Alexander Trauzzi Mar 10 '14 at 17:37
  • 1
    None, I'm afraid. It's open source, so you can certainly poke around, but I have not done so. – Mike Strobel Mar 10 '14 at 17:43
  • Heh, finding out via the source is likely well over my head, I just figured I'd ask ;) – Alexander Trauzzi Mar 10 '14 at 17:48
  • 1
    I can say that I'd be *very surprised* if any `Task` implementation explicitly created a new thread just to invoke a continuation. Unless, of course, you specify `TaskContinuationOptions.LongRunning` when registering the continuation, but using `await` never does that (as far as I know). This is completely anecdotal. – Mike Strobel Mar 10 '14 at 17:50