In a program in c# I have 2 threads apart from the main thread. When the user closes the form I want to terminate one of the threads from the main thread. How do I go about doing so?. Please provide me with the code if possible.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Please don’t use
Thread.Abortas recommended by the other answers so far, unless you want your program to be in an unknown state (see articles by Ian Griffiths and Chris Sells for more info). If closing the form should actually be killing the app, you’re probably okay – but in that case I’d recommend just using background threads anyway, which will automatically die when all foreground threads have terminated.From Joe Duffy’s ‘Concurrent Programming in Windows’:
(Synchronous thread aborts are when the thread aborts itself, rather than being aborted by another thread.)
For graceful shutdown (without risking getting into odd states) use a flag which is set periodically from the form and checked from the other threads – taking the memory model into account (e.g. either making the flag volatile or using a lock each time you test or set it). See my article on the topic for an example.