Click here to Skip to main content
15,945,119 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello friend i have Qu. that how to stop running thread. i created window form appln.
in that appln on button click i create one thread .so thread procedure contain function call from other requiement is when i click on cancel button it will show message to user that "do u want close or not" so my que. is on click of cancel button how to stop my thread as well as my function execution.
chandanadhikari 21-Jan-12 1:07am    
well not very advisable but see if DoEvents can help you out

Pausing thread has been recognized as dangerous and is not available in .NET.

Here is what you need to use instead of Pause/Resume: one of the classes: System.Threading.EventWaitHandle, System.Threading.AutoResetEvent or System.Threading.ManualResetEvent; please see:[^],[^],[^].

The first class can be used instead the other two; they are only different in the way how the event handle is reset: automatically or only explicitly.

The idea is this: the event has two states, signaled or non-signaled. One can signal the event by the call to Set and un-signal calling Reset or it will be reset automatically by a waiting thread. Now, you pause the thread by calling EventWaitHandle.WaitOne by the thread to be paused. If the event is non-signaled, the thread is put in the wait state: it is switched out by the OS and never scheduled back to execution until it is awaken. It will be awaken if some other thread calls Set on the same instance of event wait handle; it also will be awaken by a timeout (optional wait parameter) or Thread.Abort.

When a thread is awaken and the event handle uses auto-reset, it will be reset back to non-signaled state immediately on the wake-up of the thread. This transition is atomic and cannot be reliably simulated by other methods (such as Boolean condition). This auto-reset mechanism is designed to pass one and only one waiting thread at a time and make other threads waiting on the same event handle instance in the wait state.

Share this answer
Prashant Srivastava LKO 21-Jan-12 5:11am    
Satisfactory and Nice answer sir my 5
Sergey Alexandrovich Kryukov 21-Jan-12 12:31pm    
Thank you, Prashant.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900