views:

84

answers:

1

I've recently set some coursework for some undergraduate students for which they have to use a small and relatively simple C# library provided to them. The main purpose of this library is to display a simple form which is composed of a coloured grid (which they can manipulate), a number of buttons and a label with some text.

The class they extend provides a number of abstract methods which they must implement, one of which is called UpdateAction and is automatically invoked at set intervals.

I have not encountered the following problem myself but in labs some of the students have encountered an intermittent InvalidOperationException being thrown from within their UpdateAction method when they close their form. The error message is the error I would normally expect to see when you try and modify the UI from a different thread but there are just a double quote '' where you'd normally see the name of the offending control.
If this continues to be an issue we will need to reissue a fixed version of the library to them though we have already stated that this error will not impact marking of their work in any way (since it appears to be a flaw in our code).

As far as I can tell the students must be closing the form at such a point that the update is running and the controls they are modifying get disposed of before the update thread gets stopped i.e. it appears the controls have become null. The strange thing is how intermittent it is, some students have never had the issue while others have had it continually. I have never personally encountered it throughout my development of the model solutions for the coursework or in developing the library itself.

So my question is at what point in a forms life cycle do the controls on it get disposed of and therefore where would it be best to put the code that stops the update thread? Currently this code is in the forms Dispose method, would it be better placed elsewhere?

+1  A: 

How are you stopping the thread? Are you sure it is stopping before you close the window? You should ensure you stop it by setting a flag in the thread loop. You then have to wait for the thread to exit.

Thread

while (running)
{
    // thread stuff
}

Form

thread.running = false; // or use your own Stop() method that does the same thing
thread.Join();

If you want a responsive system you need to ensure the thread is able to exit within a short time of obtaining the stop signal.

Matt Breckon
yes i'm setting a flag but not doing thread.Join(), that may be the issue
RobV
Join() will ensure the UI doesn't continue until the other thread has exited
Matt Breckon