create_async如何在UI线程上运行?

时间:2018-04-21 22:58:43

标签: uwp task c++-cx ppl

假设我有一个我在UI线程上调用的函数:

IAsyncOperation<BitmapImage^>^ GetImage()
{
    return create_async([]
    {
        return create_task(GetStreamAsync())
            .then([] (Stream^ stream)
        {
            auto image = ref new BitmapImage();
            // set image properties.
            image.SetSourceAsync(stream);
            return image;
        });
    });
}

我知道内部任务也将在UI线程上执行,因为this question's answer表示默认情况下公寓知觉任务在其公寓中继续。

但是什么时候安排了create_task主体的执行?它最终会同步发生吗?或者UI线程是否等待它有空闲周期来处理异步逻辑?

1 个答案:

答案 0 :(得分:2)

让我们找出:

void ShowThread(std::string caller)
{
  std::string result{ caller + ": Current thread is " };
  result = result + std::to_string(GetCurrentThreadId());
  result = result + "\r\n";

  OutputDebugStringA(result.c_str());
}

using namespace Windows::Foundation;
using namespace Windows::Storage;

IAsyncOperation<IStorageItem^>^ GetFile()
{
  ShowThread("GetFile");
  return create_async([]
  {
    ShowThread("Inside create_async");
    return create_task(
      ApplicationData::Current->LocalFolder->TryGetItemAsync(L"foo"))
      .then([](IStorageItem^ item)
      {
        ShowThread("Inside .then");
        return item;
    });
  });
}

MainPage::MainPage()
{
  InitializeComponent();
  GetFile();
}

这显示了这样的事情:

GetFile: Current thread is 34100
Inside create_async: Current thread is 34100
Inside .then: Current thread is 34100

你可以看到他们全部在同一个线程上 - create_async立即调用它的参数(它不会将其作为任务安排)并简单地将返回值转换为{{1 }}。如果您希望继续在UI线程上,您可以这样做:

IAsyncOperation<T>

然后PPL将在任意线程上运行continuation。

相关问题