【问题标题】:How to create your own Function for Async operation in c++ UWP?如何在 C++ UWP 中创建自己的异步操作函数?
【发布时间】:2018-12-11 01:42:01
【问题描述】:

来自this,所有示例均使用Windows自带的函数进行异步操作。
是不是不能自己创建异步函数?

例如

//MainPage.xaml.h
int summation(int start_num, int stop_num);

//MainPage.xaml.cpp
int test_thread::MainPage::summation(int start_num, int stop_num)
{
    int sum = 0;
    for (start_num; start_num <= stop_num; start_num++) sum += start_num;
    return sum;
}

然后这样称呼它,

IAsyncOperation<int> sum = summation(1, 10000000000);//error
auto sumTask = Concurrency::create_task(sum);
sumTask.then(/*...*/);

我也尝试将函数定义为

//MainPage.xaml.h
IAsyncOperation<int>^ summer(int start_num, int stop_num);

但出现此错误无法重载仅通过返回类型区分的函数

【问题讨论】:

  • 你应该可以使用 lambdas,比如:create_task([]() -&gt; int { return summation(1, 100000); })

标签: c++ asynchronous uwp


【解决方案1】:

这个

    int a = 1;
    int b = 2;

    auto workItem = ref new Windows::System::Threading::WorkItemHandler([this, a, b](IAsyncAction^ workItem)
    {
        Platform::String ^ updateString = (a+b).ToString();

        //UI update
        Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
            Windows::UI::Core::CoreDispatcherPriority::High,
            ref new Windows::UI::Core::DispatchedHandler([this, updateString]()
        {
            textBlock->Text = updateString;
        }));
        //END UI upate
    });

    auto asyncAction = Windows::System::Threading::ThreadPool::RunAsync(workItem);

或者这个

    int inputPrime = platformSting2Int(textBox_primeCheck->Text);
    std::shared_ptr<bool> isItPrime = std::make_shared<bool>(true);

    auto workItem = ref new Windows::System::Threading::WorkItemHandler([this, inputPrime, isItPrime](IAsyncAction^ workItem)
    {
        *isItPrime = IsPrime(inputPrime);//IsPrime() is my custom function
    });

    auto asyncAction = Windows::System::Threading::ThreadPool::RunAsync(workItem);

    asyncAction->Completed = ref new Windows::Foundation::AsyncActionCompletedHandler([this, isItPrime](IAsyncAction^ asyncInfo, AsyncStatus asyncStatus)
    {
        if (asyncStatus == AsyncStatus::Canceled) return;

        Platform::String ^ updateString = "is not prime.";
        if(*isItPrime) updateString = "is prime.";

        //UI update
        Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(
            Windows::UI::Core::CoreDispatcherPriority::High,
            ref new Windows::UI::Core::DispatchedHandler([this, updateString]()
        {
            textBlock_primeCheckResult->Text = updateString;
        }));
        //END UI upate
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 2022-01-19
    • 2019-12-29
    • 2015-11-18
    • 1970-01-01
    • 2020-07-18
    相关资源
    最近更新 更多