4

I would like to use a ppl task to do some work in the background, and, upon completion, show the result in a window. In my case the UI-framework is MFC. The structure would be:

using namespace concurrency;

create_task([] {
    // this can be run in any thread, shouldn't be the UI thread
    // do real work here
    return 42;
}).then([](int n)
{
    // this should be run on the UI thread
    // ... open a MFC window to display results
});

The thing is, a non Windows Store app doesn't allow to specify the task_continuation_context. Instead, the runtime decides which context will be used (see task_continuation_context Class). Can I rely on the runtime to reliably figure out that it needs to run the continuation on the UI thread? Is there a reasonable workaround to achieve what I want - without blocking the UI thread?


Update: Playing around showed that the runtime will not run the continuation on the UI thread. So, is it impossible?

sorrymissjackson
  • 1,817
  • 16
  • 16

1 Answers1

0

What I did to solve this was to create a Dispatcher class and a message-only window, which is a member of the Dispatcher. The Dispatcher must be constructed (I used a singleton) from the main thread such that the main thread takes care of the messages which are sent to the message-only window. I can pass a std::function to my Dispatcher::ExecuteInMainThread function. The Dispatcher will then invoke SendMessage on the message-only window, passing in the pointer (unfortunately only a pointer will be possible) to the std::function. The only message handler I need in the message-only window will then invoke the function I passed in - within the main thread.

This Dispatcher can be used in the task continuation to execute a std::function in the main thread.

sorrymissjackson
  • 1,817
  • 16
  • 16
  • could you provide a source code example of what you did? I am trying to find out the way to do this and am running into MSDN circular reference hell, spiraling into the dark pit of MSDN no-help-whatsoever-despair. – Richard Chambers Apr 05 '18 at 15:03