I have a bunch of threaded tasks like this after each other:
create_task(somewinrtasyncfunction()).then([this(variable_that_the_last_task_returned)
{
//task here
return info;
}).then([this](info)
{
//another task here
return status});
Now I want to use status
outside the tasks, in the function that called it. How would I access it?
You
return
the task (or value) created bycreate_task(...).then(...).then(...)
.If you need to get the result synchronously, you can try calling
.get()
on thetask
but that will not work on the main UI thread(s) of your application, and is not something you should do. The code might work on a background thread today, but you might end up calling the function on the UI thread in the future -- perhaps by some very round-about fashion -- and then your app will crash. The only way to fix the app will be to re-engineer your code to be asynchronous... like it should have been in the first place.Also, note that trying to do your own work-arounds to get the value synchronously (like calling
WaitForSingleObjectEx()
on an object signaled in the task) can deadlock the UI thread for many WinRT Async methods. Don't do it!You should continue the asynchronous chain to act on the value. Here is a simple example; call
test()
from your main UI thread.Note that this example uses value-based continuations
.then([](int value){...})
rather than task-based continuations.then([](task<int> value){...})
; you would use task-based continuations if you wanted control over things like exceptions.Here's a sample run (the thread IDs will be different every time, and sometimes the last two will be the same)