Question

How can I dispatch code to run at a later time? something like :

ThreadPool.QueueUserWorkItem(callback, TimeSpan.FromSeconds(1)); // call callback() roughly one second from now
Was it helpful?

Solution

You can try the following:

System.Threading.Timer _timeoutTimer;
//...
int timeout = (int)TimeSpan.FromSeconds(1).TotalMilliseconds;
_timeoutTimer = new System.Threading.Timer(OnTimerElapsed, 
    null, timeout, System.Threading.Timeout.Infinite);
//...
void OnTimerElapsed(object state) {
     // do something
    _timeoutTimer.Dispose();
}

OTHER TIPS

You can use the Timer class for this.

Just put a sleep in your callback function. If you are using Threadpool or Task it may take longer than the actual timespan you send before getting started; this is because the thread won't start executing immediately if it's queued.

public static void MyCallback(object delay)
{
    Thread.Sleep(((TimeSpan)delay).TotalMilliseconds);
    ... code ...
}

You could do the above inline with an anonymous method and using the lower level thread construct.

new Thread(() => {
    Thread.Sleep(delayMilliseconds);
    callbackFunction();
}).Start();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top