C# 延迟操作,无内存泄漏



将操作延迟几秒钟的最佳方法是什么?我在堆栈溢出上找到了以下代码:

var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
timer.Start();
timer.Tick += (_sender, _args) =>
{
     timer.Stop();
     operation();
};

但我认为垃圾收集器不够聪明,可以从内存中删除这个计时器,因为它不知道Tick取决于Start/Stop操作,并且计时器将不再打开。

我想我需要先删除一个事件,但要做到这一点,我必须将 lambda 提取到 一个单独的方法。有没有更好的方法来简单地延迟手术?

问题是你试图延迟什么"操作"。如果它是当前的线程,那么Soner Gönül的解决方案就是要走的路。它还向应用程序发出重新调度到另一个线程的信号。

为什么不释放计时器,然后设置为 null?

var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
timer.Start();
timer.Tick += (_sender, _args) =>
{
     timer.Stop();
     //timer.Dispose(); <-- Not available on a dispatch timer
     timer = null;
     operation();
};

最新更新