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

发布于 2024-08-12 13:03:04 字数 438 浏览 4 评论 0原文

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

提前致谢...

I have a server application which needs to schedule the deferred execution of method(s). In other words, mechanism to run a method using a thread in ThreadPool after a certain period of time.

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

Please suggest an efficient mechanism to achieve above. I would prefer to avoid frequently creating new objects since above activity is likely to happen A LOT on server. Also the accuracy of call is important, i.e. while MethodX being executed after 5200 msec is fine but being executed after 6000 msec is a problem.

Thanks in advance...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ゝ偶尔ゞ 2024-08-19 13:03:04

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

You could use the RegisterWaitForSingleObject method. Here's an example:

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();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文