简体   繁体   English

C#调度代码以在以后运行?

[英]C# Dispatching code to run at a later time?

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

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

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; 如果您使用的是Threadpool或Task,则它可能比开始发送之前花费的实际时间更长。 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();

您可以为此使用Timer类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM