首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >比较使用Thread.Sleep和Timer来延迟执行

比较使用Thread.Sleep和Timer来延迟执行
EN

Stack Overflow用户
提问于 2008-12-24 15:04:36
回答 4查看 69.7K关注 0票数 63

我有一个方法,它应该延迟运行一段时间。

我应该使用

代码语言:javascript
复制
Thread thread = new Thread(() => {
    Thread.Sleep(millisecond);
    action();
});
thread.IsBackground = true;
thread.Start();

代码语言:javascript
复制
Timer timer = new Timer(o => action(), null, millisecond, -1);

我读过一些关于使用Thread.Sleep是糟糕的设计的articles。但我真的不明白为什么。

但对于定时器的使用,定时器有配置方法。由于执行被延迟了,我不知道如何处理计时器。你有什么意见建议?

或者,如果您有用于延迟执行的替代代码,也会受到欢迎。

EN

回答 4

Stack Overflow用户

发布于 2009-07-30 23:51:11

使用ThreadPool.RegisterWaitForSingleObject代替计时器:

代码语言:javascript
复制
//Wait 5 seconds then print out to console. 
//You can replace AutoResetEvent with a Semaphore or EventWaitHandle if you want to execute the command on those events and/or the timeout
System.Threading.ThreadPool.RegisterWaitForSingleObject(new AutoResetEvent(false), (state, bTimeout) => Console.WriteLine(state), "This is my state variable", TimeSpan.FromSeconds(5), true);
票数 18
EN

Stack Overflow用户

发布于 2008-12-24 15:16:33

我认为如果你真的想暂停应用程序一段特定的时间,Thread.Sleep是很好的。我认为人们之所以说它是一个糟糕的设计,是因为在大多数情况下,人们实际上并不希望应用程序暂停。

例如,我在一个pop3客户端上工作,程序员使用Thread.Sleep(1000)在套接字检索邮件时等待。在这种情况下,最好将事件处理程序连接到套接字,并在套接字完成后继续执行程序。

票数 17
EN

Stack Overflow用户

发布于 2010-07-22 14:41:48

我记得我实现了一个类似于Eric的解决方案。然而,这是一个有效的方法;)

代码语言:javascript
复制
class OneTimer
    {
        // Created by Roy Feintuch 2009
        // Basically we wrap a timer object in order to send itself as a context in order to dispose it after the cb invocation finished. This solves the problem of timer being GCed because going out of context
        public static void DoOneTime(ThreadStart cb, TimeSpan dueTime)
        {
            var td = new TimerDisposer();
            var timer = new Timer(myTdToKill =>
            {
                try
                {
                    cb();
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(string.Format("[DoOneTime] Error occured while invoking delegate. {0}", ex), "[OneTimer]");
                }
                finally
                {
                    ((TimerDisposer)myTdToKill).InternalTimer.Dispose();
                }
            },
                        td, dueTime, TimeSpan.FromMilliseconds(-1));

            td.InternalTimer = timer;
        }
    }

    class TimerDisposer
    {
        public Timer InternalTimer { get; set; }
    }
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/391621

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档