views:

394

answers:

3

In the simulation of a lan messenger in c# I have created a thread that listens to broadcast notifications from remote hosts on lan. In order to listen to the broadcast messages I am calling the sleep function and once again restarting execution of the thread. The problem with this is that when I close my form this thread continues to run.Is there any event that is invoked when I close the form?

A: 

How about Form.Closed?

Reed Copsey
A: 

Instead of a sleep function, your thread should wait for a signal from the main (form) thread (with a timeout that's equivalent to your sleep method's sleep time).

When handling the close event:

  1. The main thread should set this signal and call Thread.Join
  2. The other thread should exit the loop and finish its work
  3. The main thread then resumes its work of closing the form.
Igor Brejc
My main thread has a number of events that needs to be executed in parallel.So calling thread.join wont help.Is there anyway by which the new thread can detect the form closing event and subsequently terminate?Please provide a code snippet if possible.Thanks
Avik
Doesn't matter if you have one or many worker threads, Thread.Join is still the best way (http://stackoverflow.com/questions/263116/c-waiting-for-all-threads-to-complete). You can still use some sort of a signal which is triggered by Form.Closed and this signal can then be used by your worker threads to know that they should finish. But in general, it's best to make the main thread responsible for closing the application responsibly, not just exiting and hoping all other threads will exit too.
Igor Brejc
A: 

If you set the .IsBackground property to true on your listener thread, then it'll be closed when you shut the application down.

Form.Closing is called before the form actually closes, and Form.Close is called afterwards - you could use either of these to terminate the thread too.

Jon Artus