Main Site Documentation

Lifetime of a new thread


#1

I just posted an update to the LCD_LIveText class that emits events when a key is presses on the LCD Shield. Since the LCD_LiveText class uses an ExtendedTimer to periodically poll the keys and update the LCD the keypress events are fired in the same timer thread. For many things this would be OK, but in some cases you won’t want to call into a time consuming method directly from the timer thread as that makes the UI seem to ‘freeze’.

I used the following to generate a new thread to run my lengthy process in response to a key press event.

                    System.Threading.Thread testThread = new Thread(doSelect);
                    testThread.Start();

This works very well but leaves me wondering what the lifetime of this new thread is. When the end of the called ‘doSelect’ method is reach is the thread automatically deleted?


#2

Creating/removing threads is a complex process internally. It is not recommended to create/end threads unless necessary. instead you can sleep/pause a thread when you do not need it.

Threads die when the main thread function exits or if you kill the thread externally


#3

Yes. When you exit the thread it dies. You do not want to create a thread each time you get an interrupt.

When I am faced with a similar problem, which is often, I build a queue, into which I put work requests from interrupt routines, and have a thread processing the work requests.

I use an AutoResetEvent, which is set when something is put into the queue. The thread which processes the queue can wait on this event for work. The processing thread runs with while(true){ wait… process} type logic.

It is also necessary to control access to the queue with a lock to avoid race conditions.


#4

This is not an issue of needing to pause or sleep a thread, Gus.

I’m not creating a new thread for each event either, I’m not even creating a new instance of an Event class for each event. Most of the time what ever action pressing a button does is very quick. When I press the ‘Select’ button a series of somewhat lengthy processes begin (takes 2-3 seconds). If I use the same ‘UI’ thread the events are fired from the LCD will not be updated until the ‘lengthy’ process are finished. So, this lengthy process is now done in a new thread, and the ‘UI’ thread can go on about its business.

The whole point is to not freeze up the UI while doing a lengthy process. I assumed the thread would die when the function it called was finished but I could not find that fact referenced anywhere.