1

I am writing a small WinRT program to async create a folder and a file. The simplified code is like below:

auto createFolderOp = ApplicationData::Current->LocalFolder->CreateFolderAsync(L"DummyFolder", CreationCollisionOption::OpenIfExists);

create_task(createFolderOp).then([](task<StorageFolder ^> folder)
{
    StorageFolder ^tempFolder;

    tempFolder = uploadFolder.get();

    return tempFolder->CreateFileAsync(L"DummyFile.txt", CreationCollisionOption::ReplaceExisting);

}).then([] (task<StorageFile ^> dummyFile)
{
    StorageFile ^file;

    file = dummyFile.get();

    FileIO::WriteTextAsync(file, L"Dummy Content");
});

During the execution of this code, I want to update my UI on each step. For example I have a textblock and in each step I want to update it to show different text, such as:

Create Folder Succeed...
Create File Succeed...
Write File Succeed...

etc.

How can I access to the UI element from Async task? What is the best practice of doing this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Allan Jiang
  • 11,063
  • 27
  • 104
  • 165

2 Answers2

3

You need to update the UI from the UI thread. I wrote a post a while ago about getting to the UI thread from different types of Windows Phone apps, it should be applicable to Windows RT Apps as well: http://robwirving.com/2013/07/17/guide-to-getting-to-the-ui-thread-for-any-type-of-windows-phone-8-app/

If you're using Windows Xaml, you should be able to get the Dispatcher from the CoreWindow object and run a lambda using the dispatcher's RunAsync method.

If you're trying to get to the UI thread from a WinRT component, well that's a bit more difficult, but I have a method here: http://robwirving.com/2014/06/02/getting-to-the-ui-thread-from-a-windows-phone-winrt-component/

robwirving
  • 1,790
  • 12
  • 17
1

You can just capture the UI element variable and update it in the lambda body.

Raman Sharma
  • 4,551
  • 4
  • 34
  • 63
  • Thought I would expand on this a little bit. in your task continuation you can capture variables by object or by pointer. You can always just pass `this` to your continuation via `.then([this] (...)`. I have noticed that intellisense doesn't always pick up on the UI Elements but if you type the name out and follow it with `->` and it will usually catch on. side note: http://stackoverflow.com/questions/15119897/exception-handling-winrt-c-concurrency-async-tasks?rq=1 <- info about handling errors in tasks. – user3164339 Sep 10 '15 at 21:29