C++ equivalent of .NET's Task.Delay?

醉酒当歌 提交于 2019-12-10 13:54:42

问题


I'm writing a C++/CX component to be consumed by Window's store Apps. I'm looking for a way to accomplish what Task.Delay(1000) does in C#.


回答1:


Old Question, but still unanswered.

You can use

#include <chrono>
#include <thread>


std::this_thread::sleep_for(std::chrono::milliseconds(1000));

This will need C++11, which shouldn't be a problem when using C++/CX.




回答2:


I'm not going to claim to be a wizard - I'm still fairly new to UWP and C++/CX., but what I'm using is the following:

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;
}

The main advantage over other approaches is that:

  1. it's non-blocking
  2. You're guaranteed to be called back on the XAML UI thread



回答3:


After one year of using C++/CX, I have a general and reasonably correct answer to this question.

This link (from the Visual C++ Parallel Patterns Library documentation) includes a snippet for a function called complete_after(). That function creates a task that will complete after the specified number of milliseconds. You can then define a continuation task that will execute afterwards:

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.
    });
}

Or better yet, if you use Visual C++'s coroutines capabilities simply type:

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.
}



回答4:


You could create a concurrency::task, wait for 1000 time units and then call the ".then" method for the task. This will ensure that there is at least a wait of 1000 time units between the time you created the task and between the time it gets executed.



来源:https://stackoverflow.com/questions/13806809/c-equivalent-of-nets-task-delay

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!