1

When calling create_task is there a way to ensure that the task doesn't run on the UI thread?

I want to be sure I'm not inadvertently calling wait inside a task that somehow managed to execute on the UI thread.

rysama
  • 1,674
  • 16
  • 28

1 Answers1

2

The create_task function won't spontaneously jump onto the UI thread: if you don't call it from the UI thread it won't execute there. You need to explicitly call the Dispatcher to get back.

An apartment aware task (one which returns IAsyncAction or IAsyncOperation) will continue in its apartment by default if a task_continuation_context isn't provided to tell it otherwise. The common case of starting a task on a UI thread will continue on the UI thread.

See the Managing the thread context section of MSDN's Asynchronous programming in C++ docs for more details.

Rob Caplan - MSFT
  • 21,714
  • 3
  • 32
  • 54
  • If I create a task with use_arbitrary, am I guaranteed that the task will not execute on the UI thread? Docs just say the OS will choose; I'd like to be certain it's not going to somehow choose the UI thread. Also, I'm getting unexpected results when creating tasks on the UI thread. Creating a task on the UI thread and then calling "wait" from within, doesn't hang/crash the app like I would expect. This makes me think that, despite what the docs say, calling create_task on the UI thread doesn't actually execute the task on the UI thread (even when I specified use_current). Is this correct? – rysama May 09 '15 at 10:00
  • `use_arbitrary` is just that - any thread. If you don't want it on the UI thread, use a `ThreadPool` thread. Please provide code sample for what you are doing - "within" and "inside" are ambiguous without code. – Peter Torr - MSFT May 09 '15 at 23:36