入力候補ソース サンプル

注意

このトピックのサンプル コードの代わりとして、cpp-async GitHub リポジトリに、本番環境対応バージョンのタスク完了ソース実装のソース コードがあります。

このトピックでは、.NET の TaskCompletionSource のような、独自の入力候補ソース クラスを作成して使用する方法を示します。

completion_source サンプルのソース コード

以下の一覧のコードは、サンプルとして提供されています。 その目的は、独自のバージョンを記述する方法を説明することです。 たとえば、取り消しやエラー伝達のサポートは、このサンプルの対象外です。

#include <winrt/base.h>
#include <windows.h>

template <typename T>
struct completion_source
{
    completion_source()
    {
        m_signal.attach(::CreateEvent(nullptr, true, false, nullptr));
    }

    void set(T const& value)
    {
        m_value = value;
        ::SetEvent(m_signal.get());
    }

    bool await_ready() const noexcept
    {
        return ::WaitForSingleObject(m_signal.get(), 0) == 0;
    }

    void await_suspend(std::experimental::coroutine_handle<> resume)
    {
        m_wait.attach(winrt::check_pointer(::CreateThreadpoolWait(callback, resume.address(), nullptr)));
        ::SetThreadpoolWait(m_wait.get(), m_signal.get(), nullptr);
    }

    T await_resume() const noexcept
    {
        return m_value;
    }

private:

    static void __stdcall callback(PTP_CALLBACK_INSTANCE, void* context, PTP_WAIT, TP_WAIT_RESULT) noexcept
    {
        std::experimental::coroutine_handle<>::from_address(context)();
    }

    struct wait_traits
    {
        using type = PTP_WAIT;

        static void close(type value) noexcept
        {
            ::CloseThreadpoolWait(value);
        }

        static constexpr type invalid() noexcept
        {
            return nullptr;
        }
    };

    winrt::handle m_signal;
    winrt::handle_type<wait_traits> m_wait;
    T m_value{};
};

入力候補を別のコルーチンにオフロードする

このセクションでは、completion_source の 1 つの使用例を紹介します。 Windows コンソール アプリケーション (C++/WinRT) プロジェクト テンプレートに基づいて Visual Studio で新しいプロジェクトを作成し、次のコード リストを main.cpp に貼り付けます (前のセクションの一覧に基づいて completion_source の定義を展開します)。

// main.cpp
#include "pch.h"

#include <winrt/base.h>
#include <windows.h>

template <typename T>
struct completion_source
{
    ... // Paste the listing of completion_source here.
}

using namespace std::literals;
using namespace winrt;
using namespace Windows::Foundation;

fire_and_forget CompleteAfterFiveSecondsAsync(completion_source<bool>& completionSource)
{
    co_await 5s;
    completionSource.set(true);
}

IAsyncAction CompletionSourceExample1Async()
{
    completion_source<bool> completionSource;
    CompleteAfterFiveSecondsAsync(completionSource);
    co_await completionSource;
}

int main()
{
    auto asyncAction { CompletionSourceExample1Async() };
    puts("waiting");
    asyncAction.get();
    puts("done");
}

クラス内の completion_source をカプセル化し、値を戻す

この次の例では、単純な App クラスを使用して completion_source をカプセル化し、完了時に値を返します。 Windows コンソール アプリケーション (C++/WinRT) プロジェクト テンプレートに基づいて Visual Studio で新しいプロジェクトを作成し、次のコード リストを main.cpp に貼り付けます (前のセクションの一覧に基づいて completion_source の定義を展開します)。

// main.cpp
#include "pch.h"

#include <winrt/base.h>
#include <windows.h>

template <typename T>
struct completion_source
{
    ... // Paste the listing of completion_source here.
}

using namespace std::literals;
using namespace winrt;
using namespace Windows::Foundation;

struct App
{
    completion_source<winrt::hstring> m_completionSource;

    IAsyncOperation<winrt::hstring> CompletionSourceExample2Async()
    {
        co_return co_await m_completionSource;
    }

    winrt::fire_and_forget CompleteAfterFiveSecondsAsync()
    {
        co_await 5s;
        m_completionSource.set(L"Hello, World!");
    }
};

int main()
{
    App app;
    auto asyncAction{ app.CompletionSourceExample2Async() };
    app.CompleteAfterFiveSecondsAsync();
    puts("waiting");
    auto message = asyncAction.get();
    printf("%ls\n", message.c_str());
}