【发布时间】:2012-11-28 05:05:34
【问题描述】:
我正在编写一个 C++/CX 组件,供 Window 的商店应用程序使用。我正在寻找一种方法来完成 Task.Delay(1000) 在 C# 中所做的事情。
【问题讨论】:
标签: task wait windows-store-apps c++-cx
我正在编写一个 C++/CX 组件,供 Window 的商店应用程序使用。我正在寻找一种方法来完成 Task.Delay(1000) 在 C# 中所做的事情。
【问题讨论】:
标签: task wait windows-store-apps c++-cx
老问题,但仍未得到解答。
你可以使用
#include <chrono>
#include <thread>
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
这将需要C++11,这在使用 C++/CX 时应该不是问题。
【讨论】:
在使用 C++/CX 一年之后,我对这个问题有了一个普遍且合理正确的答案。
This link(来自 Visual C++ 并行模式库文档)包含一个用于名为 complete_after() 的函数的 sn-p。该函数创建一个将在指定的毫秒数后完成的任务。然后,您可以定义一个随后将执行的延续任务:
void MyFunction()
{
// ... Do a first thing ...
concurrency::create_task(complete_after(1000), concurrency::task_continuation_context::use_current)
.then([]() {
// Do the next thing, on the same thread.
});
}
或者更好的是,如果您使用 Visual C++ 的 coroutines 功能,只需键入:
concurrency::task<void> MyFunctionAsync()
{
// ... Do a first thing ...
co_await complete_after(1000);
// Do the next thing.
// Warning: if not on the UI thread (e.g., on a threadpool thread), this may resume on a different thread.
}
【讨论】:
concurrency::task<void> :/ 哦,concurrency::wait(ms) 看起来很有希望 :)
您可以创建一个 concurrency::task,等待 1000 个时间单位,然后为该任务调用“.then”方法。这将确保在您创建任务和执行任务之间至少有 1000 个时间单位的等待。
【讨论】:
我不会声称自己是个巫师——我对 UWP 和 C++/CX 还是很陌生,但我使用的是以下内容:
public ref class MyClass sealed {
public:
MyClass()
{
m_timer = ref new Windows::UI::Xaml::DispatcherTimer;
m_timer->Tick += ref new Windows::Foundation::EventHandler<Platform::Object^>(this, &MyClass::PostDelay);
}
void StartDelay()
{
m_timer->Interval.Duration = 200 * 10000;// 200ms expressed in 100s of nanoseconds
m_timer->Start();
}
void PostDelay(Platform::Object^ sender, Platform::Object ^args)
{
m_timer->Stop();
// Do some stuff after the delay
}
private:
Windows::UI::Xaml::DispatcherTimer ^m_timer;
}
与其他方法相比的主要优势在于:
【讨论】: