系统.线程.定时器

发布于 2024-10-08 02:05:12 字数 426 浏览 1 评论 0原文

当我们使用System.Threading.Timer时,那么该方法是在创建计时器的线程上执行的吗?或者 ir 是在另一个线程中执行的?

class Timer
{
    static void Main()
    {
        TimerCallback tcall = statusChecker.CheckStatus;
        Timer stateTimer = new Timer(tcb, autoEvent, 1000, 250);
    }
}
class StatusChecker
{
    public void CheckStatus(Object stateInfo)
    {
    }
}

我的问题是计时器委托(CheckStatus)调用的方法是在主线程中执行还是在另一个线程中执行?

When we use System.Threading.Timer, then is the method executed on the thread that created the timer? Or is ir executed in another thread?

class Timer
{
    static void Main()
    {
        TimerCallback tcall = statusChecker.CheckStatus;
        Timer stateTimer = new Timer(tcb, autoEvent, 1000, 250);
    }
}
class StatusChecker
{
    public void CheckStatus(Object stateInfo)
    {
    }
}

My question is if the method called by the timer delegate (CheckStatus) is executed in main thread or is it executed in another thread?

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

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

发布评论

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

评论(3

抹茶夏天i‖ 2024-10-15 02:05:12

System.Threading.Timer 将在线程池中的另一个线程上执行其工作。

System.Windows.Forms.Timer 将在现有 (GUI) 线程上执行。

System.Threading.Timer will execute its work on another thread in the thread pool.

System.Windows.Forms.Timer will execute on the existing (GUI) thread.

朦胧时间 2024-10-15 02:05:12

文档说如下:

为回调指定的方法应该是可重入的,因为它是在 ThreadPool 线程上调用的。

所以回调几乎肯定会在另一个线程上。

当然,如果您从 ThreadPool 线程启动计时器,它有可能在同一线程上执行,但不能保证。

The docs say the following:

The method specified for callback should be reentrant, because it is called on ThreadPool threads.

So the callback will almost certainly be on another thread.

Of course, if you launch the timer from a ThreadPool thread, there's a chance it might execute on the same thread, but no guarantee.

愚人国度 2024-10-15 02:05:12

MSDN 指出:

使用TimerCallback委托指定您希望Timer执行的方法。计时器委托是在构造计时器时指定的,并且不能更改。该方法不在创建计时器的线程上执行;它在系统提供的ThreadPool线程上执行。

因此,在您的示例中,计时器委托 (CheckStatus) 将在单独的线程中执行。

MSDN States:

Use a TimerCallback delegate to specify the method you want the Timer to execute. The timer delegate is specified when the timer is constructed, and cannot be changed. The method does not execute on the thread that created the timer; it executes on a ThreadPool thread supplied by the system.

Hence, in your example, timer delegate (CheckStatus) would be executed in an seperate thread.

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