Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>From the code you've included in the question, it <em>looks</em> like you aren't storing a reference to <code>timer</code> anywhere. I could be wrong, but my guess is that you're not seeing the callback repeated because the timer object itself has been garbage collected. Assign a reference to the timer to a longer-lived variable (i.e., a field) and I'd wager that will resolve the problem.</p> <p>In other words, I don't think the <code>for</code> loop has anything to do with what you're seeing (I'm not disputing the evidence, just proposing that it's coincidental and nothing else).</p> <p>To test my hypothesis, I created the following very simple Windows Forms app:</p> <pre><code>using System; using System.Threading; using System.Windows.Forms; using Timer = System.Threading.Timer; public class Program { static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new TestForm()); } } class TestForm : Form { protected override void OnLoad(EventArgs e) { base.OnLoad(e); var timer = new Timer(TimerProc, null, 1000, 1000); } public void TimerProc(object state) { for (int i = 0; i &lt;= 6; i++) { Console.WriteLine(DateTime.Now.ToLongTimeString()); } } } </code></pre> <p>I saw the current time print to the console for a little more than thirty seconds; then it stopped.</p> <p>In contrast, the following change appears to resolve the problem.</p> <pre><code>class TestForm : Form { // Note: declare a field to store a reference to the timer. Timer timer; protected override void OnLoad(EventArgs e) { base.OnLoad(e); this.timer = new Timer(TimerProc, null, 1000, 1000); } // ... } </code></pre> <p>I started the program again after making the above change, and the timer has continued firing for a few minutes.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload