Click here to Skip to main content
15,922,584 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hey, im working on an example for making a thread start and stop and continue after stoping
i wrote code for starting but i didn't know how to stop the same thread

private void startBtn_Click(object sender, EventArgs e)
        {
            //START BG WORKER
            backgroundWorker1.RunWorkerAsync();
            Thread thr = new Thread(Start);
            thr.SetApartmentState(ApartmentState.STA);
            thr.Start();
        }
        static void Start()
        {
            var dr = new ChromeDriver();
            dr.Navigate().GoToUrl("http://www.google.com");
            dr.Navigate().GoToUrl("http://www.facebook.com");
        }
        private void cancelBtn_Click(object sender, EventArgs e)
        {
        }
        private void contiBtn_Click(object sender, EventArgs e)
        {
        }


What I have tried:

how to start,stop,resume a thread in c#
Posted
Updated 23-Jun-17 0:03am
Comments
George Swan 23-Jun-17 15:59pm    
I don’t think it is wise to be stopping and restarting threads. Those sort of actions block threads and cause inefficient use of the thread pool. My recommendation, for what it’s worth, would be to abandon the use of the BackgroundWorker and adopt the modern asynchronous techniques provided by the Task based async await asynchronous framework. These techniques give sufficient abstraction for you not to have to marshal threads directly.

Basically, it's not recommended: there are methods in the Thread class to do it - Suspend and Resume - but they are depreciated and for good reasons! It's not a safe thing to do: it can lead to deadlocks and similar problems as the "suspending" thread has no real idea what the "suspended" thread was doing when it was stopped. That's not good, not at all.

See here: Pausing and Resuming Threads[^]
A better idea to use use thread synchronisation - see here: Overview of Synchronization Primitives[^]
 
Share this answer
 
Reading people the lines I think you need to just build extra logic into your code so it knows when to stop and when to continue rather than pausing and resuming the thread.

public class Navigator
{
    private bool isRunning;
    private Thread thread;
    private ManualResetEvent resetEvent = new ManualResetEvent(true);

    public List<string> Urls { get; set; }

    public Navigator()
    {
        this.isRunning = false;
        this.Urls = new List<string>();
    }

    public void Start()
    {
        if (this.isRunning)
        {
            return;
        }

        this.isRunning = true;

        thread = new Thread(Process);
        thread.Start();
    }

    private void Process()
    {
        foreach (string url in this.Urls)
        {
            // if the isRunning flag is cleared then drop out of the loop
            if (!this.isRunning)
            {
                return;
            }

            Debug.WriteLine(string.Format("Processing {0}", url));
            Thread.Sleep(3000); // simulates doing work

            // if "unset" the thread will wait here otherwise it will continue
            resetEvent.WaitOne();
        }
    }

    public void Pause()
    {
        // unset the reset event which will cause the loop to pause
        this.resetEvent.Reset();
        Debug.WriteLine("Paused");
    }

    public void Resume()
    {
        // set the reset event which will cause the loop to continue
        this.resetEvent.Set();
        Debug.WriteLine("Resumed");
    }

    public void Stop()
    {
        Debug.WriteLine("Stopping...");

        // set a flag that will abort the loop
        this.isRunning = false;

        // set the event incase we are currently paused
        this.resetEvent.Set();

        // wait for the thread to finish
        this.thread.Join();

        Debug.WriteLine("Stopped");
    }
}


private Navigator nav;

public Form1()
{
    InitializeComponent();
}

private void startBtn_Click(object sender, EventArgs e)
{
    this.nav = new Navigator();

    nav.Urls.Add("http://www.url1.com");
    nav.Urls.Add("http://www.url2.com");
    nav.Urls.Add("http://www.url3.com");
    nav.Urls.Add("http://www.url4.com");
    nav.Urls.Add("http://www.url5.com");
    nav.Urls.Add("http://www.url6.com");
    nav.Urls.Add("http://www.url7.com");
    nav.Urls.Add("http://www.url8.com");
    nav.Urls.Add("http://www.url9.com");
    nav.Urls.Add("http://www.url10.com");

    nav.Start();
}

private void pauseBtn_Click(object sender, EventArgs e)
{
    if (this.nav == null)
    {
        return;
    }

    nav.Pause();
}

private void resumeBtn_Click(object sender, EventArgs e)
{
    if (this.nav == null)
    {
        return;
    }

    nav.Resume();
}

private void stopBtn_Click(object sender, EventArgs e)
{
    StopProcess();
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    StopProcess();
}

private void StopProcess()
{
    if (this.nav == null)
    {
        return;
    }

    nav.Stop();
}
 
Share this answer
 
Comments
Ilyas Zahir 23-Jun-17 14:10pm    
hey please i didn't understand first code if you have any tutorial to understand it please share it with me or if u could do the same with my code please

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