在将来的某个时间调用单个操作的最佳方法?

noc*_*ura 3 .net c# lambda

我希望在未来的某个时刻启动计时器以执行一次.我想使用lambda表达式来简化代码.所以我想做点什么......

(new System.Threading.Timer(() => { DoSomething(); },
                    null,  // no state required
                    TimeSpan.FromSeconds(x), // Do it in x seconds
                    TimeSpan.FromMilliseconds(-1)); // don't repeat
Run Code Online (Sandbox Code Playgroud)

我觉得它很整洁.但在这种情况下,不会丢弃Timer对象.解决这个问题的最佳方法是什么?或者,我应该在这里做一个完全不同的方法吗?

小智 5

这将完成你想要的,但我不确定它是最好的解决方案.我认为它的东西短而优雅,但可能比它的价值更令人困惑和难以理解.

System.Threading.Timer timer = null;
timer = new System.Threading.Timer(
    (object state) => { DoSomething(); timer.Dispose(); }
    , null // no state required
    ,TimeSpan.FromSeconds(x) // Do it in x seconds
    ,TimeSpan.FromMilliseconds(-1)); // don't repeat
Run Code Online (Sandbox Code Playgroud)


Mat*_*ela 5

这种方法是有缺陷的。
您正在内存中创建一个没有引用的对象。这意味着计时器对象可被垃圾收集。虽然此代码有时会起作用,但您无法预测垃圾收集何时启动并删除计时器。

例如,在下面的代码中,我强制进行垃圾收集,这会导致计时器永远不会触发。

static void Main(string[] args)
{
    DoThing();
    GC.Collect();
    Thread.Sleep(5000);
}


static void DoThing()
{
    new System.Threading.Timer(x => { Console.WriteLine("Here"); },
            null,  
            TimeSpan.FromSeconds(1), 
            TimeSpan.FromMilliseconds(-1));
}
Run Code Online (Sandbox Code Playgroud)