Implementing Asynchronous Delay in C ++ / CX

I am trying to write a function that, taking into account a few seconds and a callback, starts a callback after a given number of seconds. The callback does not have to be in the same thread. The target language is C ++ / CX.

I tried using Windows :: System :: Threading :: ThreadPoolTimer, but the result is a memory access exception. The problem is that the callback implementation (in native C ++) cannot be accessed from the managed thread to which the timer executes its callback.

ref class TimerDoneCallback {
private:
    function<void(void)> m_callback;
public:
    void EventCallback(ThreadPoolTimer^ timer) {
        m_callback(); // <-- memory exception here
    }
    TimerDoneCallback(function<void(void)> callback) : m_callback(callback) {}
};
void RealTimeDelayCall(const TimeSpan& duration, function<void(void)> callback) {
    auto t = ref new TimerDoneCallback(callback);
    auto e = ref new TimerElapsedHandler(t, &TimerDoneCallback::EventCallback);
    ThreadPoolTimer::CreateTimer(e, duration);
}
void Test() {
    RealTimeDelayCall(duration, [](){}); //after a delay, run 'do nothing'
}

I do not want to create a thread and sleep on it, because there can be many simultaneous delays.

+5
source share
1 answer

TimerDoneCallback - ++/CX ( ). , :

auto e = ref new TimerElapsedHandler(t, &TimerDoneCallback::EventCallback, CallbackContext::Any, true);

bool , false . (False - .)

PPL : http://msdn.microsoft.com/en-us/library/hh873170(v=vs.110).aspx, ThreadPoolTimer.

+3

All Articles