猿问

系统.线程.计时器在 c 中超过 2 秒的到期时间不工作#

我正在使用System.Threading.Timer使我的当前线程等待特定的时间。我没有使用任何间隔,因为我不希望函数重复自身。我的代码的问题在于,我的计时器不适用于超过 2 秒的到期时间值。是内存问题还是代码中的某些错误。任何人都可以帮忙。谢谢。这是我的示例代码。


   var timer = new System.Threading.Timer(a =>

                {

                   //Stuff to perform after 10 seconds


                }, null, 10000, 0);


慕运维8079593
浏览 97回答 1
1回答

守候你守候我

您需要确保将 指向 的引用保存在某个位置,以防止它被垃圾回收。有关此内容的更多信息,请参阅此帖子。timerclass DontGarbageCollect{    static System.Threading.Timer timer;    public void ShowTimer() {        // Store timer in this.timer to prevent garbage collection        timer = new System.Threading.Timer(a =>            {               //Stuff to perform after 10 seconds            }, null, 10000, 0);    }}
随时随地看视频慕课网APP
我要回答