我有一个方法,它应该延迟运行一段时间。
我应该使用
Thread thread = new Thread(() => {
Thread.Sleep(millisecond);
action();
});
thread.IsBackground = true;
thread.Start();
或
Timer timer = new Timer(o => action(), null, millisecond, -1);
我读过一些关于使用Thread.Sleep
是糟糕的设计的articles。但我真的不明白为什么。
但对于定时器的使用,定时器有配置方法。由于执行被延迟了,我不知道如何处理计时器。你有什么意见建议?
或者,如果您有用于延迟执行的替代代码,也会受到欢迎。
发布于 2009-07-30 23:51:11
使用ThreadPool.RegisterWaitForSingleObject
代替计时器:
//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);
发布于 2008-12-24 15:16:33
我认为如果你真的想暂停应用程序一段特定的时间,Thread.Sleep是很好的。我认为人们之所以说它是一个糟糕的设计,是因为在大多数情况下,人们实际上并不希望应用程序暂停。
例如,我在一个pop3客户端上工作,程序员使用Thread.Sleep(1000)在套接字检索邮件时等待。在这种情况下,最好将事件处理程序连接到套接字,并在套接字完成后继续执行程序。
发布于 2010-07-22 14:41:48
我记得我实现了一个类似于Eric的解决方案。然而,这是一个有效的方法;)
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; }
}
https://stackoverflow.com/questions/391621
复制相似问题