【问题标题】:Best way to schedule deferred execution of method using ThreadPool?使用 ThreadPool 安排延迟执行方法的最佳方法?
【发布时间】:2009-11-25 11:09:11
【问题描述】:

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

提前谢谢...

【问题讨论】:

    标签: c# .net multithreading scheduling


    【解决方案1】:

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

    【讨论】:

    • 我认为值得一提的是,任何希望以重复方式(最后一个参数为 false)使用它的人都希望捕获返回的 RegisteredWaitHandle 对象,以便稍后您可以调用 @987654324 @ 方法来防止任何进一步的执行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多