Click here to Skip to main content
15,869,972 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
My Windows form has two buttons: "Start" and "Stop". How can I stop the form from doing whatever it is doing without closing the whole application? The "Stop" button would have to stop a process that's being run in another class.

What I have tried:

in my application i am doing operation using timer and thread
Posted
Updated 10-Oct-18 21:34pm
v3
Comments
Richard MacCutchan 7-Apr-16 6:00am    
It depends what the process is doing and what you want to happen when the user clicks stop. You could set a global flag that the process can check, or use an event handler.

It depends on the implementation of the process you want to stop, but you normally flag something on it that tells it you want it to stop.

C#
class Program
{
    static void Main(string[] args)
    {
        Worker w = new Worker();

        Thread t = new Thread(new ThreadStart(w.DoWork));
        t.Start();

        Console.WriteLine("Press any key to stop");
        Console.ReadKey();
            
        Console.WriteLine("Stopping worker...");
        w.Stopping = true;
        t.Join();

        Console.WriteLine("Worker stopped");
    }
}

class Worker
{
    public bool Stopping { get; set; }

    public void DoWork()
    {
        while (!Stopping)
        {
            System.Diagnostics.Debug.WriteLine (DateTime.Now);
            System.Threading.Thread.Sleep(1000);
        }
    }
}
 
Share this answer
 
Either you can use Thread.Stop() on stop button or you can directly call
C#
Environment.Exit(1)

to stop immediately.
 
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