使用ThreadPool安排延迟执行方法的最佳方法?

时间:2009-11-25 11:09:12

标签: c# .net multithreading scheduling

我有一个服务器应用程序需要安排延迟执行方法。换句话说,在一段时间后使用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);

请建议一种有效的机制来实现上述目标。我宁愿避免频繁创建新对象,因为上述活动很可能在服务器上发生。呼叫的准确性也很重要,即在5200毫秒之后执行MethodX很好但在6000毫秒之后执行是一个问题。

提前致谢...

1 个答案:

答案 0 :(得分:4)

您可以使用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();
    }
}