我有一个服务器应用程序,需要安排方法的延迟执行。换句话说,就是在一段时间后使用ThreadPool中的线程运行方法的机制。
void ScheduleExecution (int delay, Action someMethod){
//How to implement this???
}
//At some other place
//MethodX will be executed on a thread in ThreadPool after 5 seconds
ScheduleExecution (5000, MethodX);
请建议一种有效的机制来实现上述目标。我宁愿避免频繁创建新对象,因为上述事件很可能在服务器上发生很多。另外,调用的准确性也很重要,即 MethodX 在 5200 毫秒后执行还可以,但在 6000 毫秒后执行就会出现问题。
提前致谢...
最佳答案
您可以使用RegisterWaitForSingleObject方法。这是一个例子:
public class Program
{
static void Main()
{
var waitHandle = new AutoResetEvent(false);
ThreadPool.RegisterWaitForSingleObject(
waitHandle,
// Method to execute
(state, timeout) =>
{
Console.WriteLine("Hello World");
},
// optional state object to pass to the method
null,
// Execute the method after 2 seconds
TimeSpan.FromSeconds(2),
// Execute the method only once. You can set this to false
// to execute it repeatedly every 2 seconds
true);
Console.ReadLine();
}
}
关于c# - 使用线程池安排方法延迟执行的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1796232/