windows C++-任务完成源的创建

发布于:2024-08-17 ⋅ 阅读:(88) ⋅ 点赞:(0)

Task Completion Source 可以理解为创建的任务等待异步任务的完成,它的状态由 Task Completion Source 上的方法显式控制。 这样就可以将外部异步操作的完成传播到基础任务。 分离还可确保使用者在无法访问相应的 TaskCompletionSource 的情况下无法转换状态。下面介绍如何创作和使用自己的完成源类,类似于 .NET 的 TaskCompletionSource。

一个常见的案例就是异步转同步,例如下面的代码:

// 1. 异步方法
private static async Task<string> WithResultAsync()
    {
        Debug.WriteLine("1. task start……");
        await Task.Delay(1000);
        Debug.WriteLine("2. taskend……");
        return "1 second wait...";
    }

/* 2. 使用TaskCompletionSource将此异步方法转成同步

    2.1 获取var sourceTask =TaskCompletionSource.Task
    2.2 等待此sourceTask结果-sourceTask.Result
    2.3 设置设置sourceTask.Result的结果值
*/

private void TaskButton_OnClick(object sender, RoutedEventArgs e)
    {
         var result = AwaitByTaskCompleteSource(WithResultAsync);
    }

private string AwaitByTaskCompleteSource(Func<Task<string>> func)
    {
        var taskCompletionSource = new TaskCompletionSource<string>();
        var task1 = taskCompletionSource.Task;
        Task.Run(async () =>
        {
            var result = await func.Invoke();
            taskCompletionSource.SetResult(result);
        });
        var task1Result = task1.Result;
        Debug.WriteLine($"AwaitByTaskCompleteSource end:{task1Result}");
        return task1Result;
    }

译者按: 我认为C#可能比C++能够更加准确的说明这个问题。 

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 的一个用例。 在 Visual Studio 中创建一个基于 Windows 控制台应用程序 (C++/WinRT) 项目模板的新项目,然后将以下代码清单粘贴到 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,并在完成时返回值。 在 Visual Studio 中创建一个基于 Windows 控制台应用程序 (C++/WinRT) 项目模板的新项目,然后将以下代码清单粘贴到 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());
}


网站公告

今日签到

点亮在社区的每一天
去签到