Avik
Avik

Reputation: 2137

Event to close form

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?

Upvotes: 1

Views: 1055

Answers (3)

Jon Artus
Jon Artus

Reputation: 6358

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.

Upvotes: 2

Igor Brejc
Igor Brejc

Reputation: 19014

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.

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564931

How about Form.Closed?

Upvotes: 0

Related Questions