Click here to Skip to main content
15,920,801 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi everyone.

I hope someone can help.

I have a program with a thread that starts a method called MethodRunner(), which runs the rest of the methods in my program. Everything works fine, but I need a way of stopping the methods if the user clicks an "Abort" button.

I cant seem to get it to work.

my abort button calls RequestStop();

public void RequestStop()
        {
            _shouldStop = true;
        }

and then my thread to run methods...

public void StartThread()
       {
           //Creates and starts the thread
           Thread workerThread = new Thread(MethodRunner);
           workerThread.Start();
       }
       public void MethodRunner()
       {
           while (!_shouldStop)
           {
               //Run Methods
           }
}

As i say the app runs fine, its just the abort button that wont work. Thread.Abort(); works, but it gives an annoying pop up msg, and I've read that its not a good idea to use the abort method.
I thought I might have the while(!_shouldStop) in the wrong place but I've tried moving it elsewhere with no luck.
Chris


Any suggestions?

Thanks very much

Chris
Posted
Updated 14-Oct-10 5:41am
v2

A simple way is a variable (for example abortMethodRunner) that both the main thread and the MethodRunner thread can reach. In the actual method of the MethodRunner thread there must be an occasional check to see if it should abort, something like:

while(HasMoreWorkItems && !abortMethodRunner)
{
  // process work item
} 


Good luck!
 
Share this answer
 
If you run the methods using a Background worker than you can have the accept button fire the BackgroundWorkers cancel event.

Don't forget to have the background worker accept cancel signals.
 
Share this answer
 
What does clicking the Abort button do? Show us the code.
 
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