Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The thread has exited with code 0 in Windows Forms

I have problem with exiting threads in my Windows Forms.

I have classic Windows Forms, which is running. I need to do something every period of time, 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);

Method DoSomething is called by few threads (main thread and this timer), so I covered it that way:

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 good, until my timer thread just exits with message:

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

Same thing happens to my FileSystemWatcher, which also calls DoSomething Method. Both events are independent and exit at random time (at least I did not find any rule for it)

What causes this situation and how can I prevent it?

like image 384
Peter Avatar asked Mar 24 '23 07:03

Peter


2 Answers

If you don't keep a reference to the timer object, it will be garbage collected.

Looking at the code that you've posted, it doesn't appear that you are keeping hold of the reference. You will need to make it a field in your containing class, rather than a local variable.

The timer can also get garbage collected if you declare it at the start of a long-running method and don't reference it later in the method.

You can fix that particular problem by adding GC.KeepAlive(timer); near the end of the method as described here.

like image 117
Matthew Watson Avatar answered Apr 01 '23 13:04

Matthew Watson


It sounds like the Timer is getting garbage collected. Make it an instance variable of the form so that you can hold on to the reference.

like image 20
Mufaka Avatar answered Apr 01 '23 14:04

Mufaka