Thread exited with code 0 in Windows Forms

I have a problem with thread exits in Windows Forms.

I have classic Windows Forms that works. I need to do something every time period, so I added:

TimerCallback timerDelegate = new TimerCallback(this.TryDoSomething); int period = 10 * 1000; // to miliseconds System.Threading.Timer stateTimer = new System.Threading.Timer(timerDelegate, null, period, period); 

The DoSomething method is called by several threads (the main thread and this timer), so I covered it as follows:

 private void TryDoSomething(object o) { lock (tryDoSomethingMutex) { if (this.dataGridView1.InvokeRequired) { RefreshCallback d = new RefreshCallback(DoSomething); this.Invoke(d, new object[] { o }); } else { this.DoSomething(o); } } } 

And everything works fine until my timer thread just comes up with a message:

 The thread 0x2798 has exited with code 0 (0x0). 

The same thing happens with my FileSystemWatcher, which also calls the DoSomething method. Both events are independent and exit at any time (at least I did not find any rule for it)

What causes this situation and how can I prevent it?

+4
source share
2 answers

If you do not save the reference to the timer object, this will collect garbage.

Looking at the code that you posted does not seem to keep the link to the link. You will need to make this field in your containing class, not a local variable.

A timer can also receive garbage collection if you declare it at the beginning of a long-term method and do not refer to it later in the method.

You can fix this specific problem by adding GC.KeepAlive(timer); closer to the end of the method as described here .

+4
source

Timer seems to be collecting garbage. Make it a form instance variable so that you can hold the link.

+3
source

All Articles