c# - 使用线程池安排方法延迟执行的最佳方法?

标签 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);

请建议一种有效的机制来实现上述目标。我宁愿避免频繁创建新对象,因为上述事件很可能在服务器上发生很多。另外,调用的准确性也很重要,即 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/

相关文章:

c# - 使用 LinqToExcel 读取保存为 xls 的 xlsx

c# - 从 MVC Controller 调用 Web API

c# - 合并两个列表列表

c# - .NET 和 SQL Server - Datetime 还是 DateTimeOffset?

c# - 在多个线程中锁定一个变量

c# - 字符串的持久哈希码

c# - 为什么不允许条件属性方法返回 void 以外的值

.net - CPU 负载较重时跨线程 BeginInvoke 阻塞

java - 从哪里开始异步任务 - Android

Java:notify() 与 notifyAll() 重来一遍