Garbage collection and threads

I’ve been working on a project involving a Psion Teklogix Netpad 5522. Nice “little” thing BTW.

Anyway, I needed multiple threads running simultaneously (one which checks for a wireless network connection). Normal threading isn’t possible because of the limitations of the compact framework. So I used timers that invoked a method at a certain interval. This worked just fine, with one, hard to find error. When the application is stopped there was an ObjectDisposedException, sometimes :S.

After looking arround and trying out quite a bit, I got a solution to this problem. It seems that when the garbagedisposal disposes of object the thread is addressing the error occurs. This is how I solved it.

You create a public boolean that’s false by default. You set it true the first thing when you start the thread method and false the last thing before leaving it. This way you can check if the thread method it running.

Then override the OnClosing() method like this:

protected override void OnClosing(System.ComponentModel.CancelEventArgs e) {
   while (boolconnectioncheckrunning) {

A few words of explaination:

  1. this.connectionchecktimer.Dispose(); will force the timer to be disposed first. This way the thread cannot be started again.
  2. while (boolconnectioncheckrunning)

    This will make sure you don’t continue to the close call before the thread is finished.
  3. Finally call the close method so all the rest of the application can be recycled by the garbagecollector

It isn’t what you’re learned at school but it works like a charm 😉