从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);
但是收到此错误无法重载仅由返回类型区分的函数
答案 0 :(得分:0)
此
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
});