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();
}
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, [](){});
}
I do not want to create a thread and sleep on it, because there can be many simultaneous delays.
source
share