开始停止恢复线程C# [英] Start stop resume a thread C#

查看:67
本文介绍了开始停止恢复线程C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我正在制作一个线程启动和停止的示例,并在停止后继续

i编写代码启动但我不知道如何停止同一个线程



 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)
{
}





我的尝试:



如何启动,停止,恢复c#中的线程

解决方案

基本上,不推荐:Thread类中有方法可以执行此操作 - 暂停和恢复 - 但他们是折旧的,有充分的理由!这不是一件安全的事情:它可能导致死锁和类似的问题,因为暂停线程并不知道暂停线程在停止时正在做什么。这不好,完全没有。



见这里:暂停和恢复线程 [ ^ ]

使用线程同步更好的主意 - 请参阅此处:同步基元概述 [ ^ ]


读取我认为你需要的行只是在代码中构建额外的逻辑,以便知道何时停止和何时继续而不是暂停和恢复线程。



公共课导航器
{
private bool isRunning;
私有线程线程;
private ManualResetEvent resetEvent = new ManualResetEvent(true);

public List< string>网址{get;组; }

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(this.Urls中的字符串url)
{
//如果isRunning如果(!this.isRunning)
{
return;则清除该标志然后退出循环

}

Debug.WriteLine(string.Format(Processing {0},url));
Thread.Sleep(3000); //模拟做工作

//如果未设置线程将在这里等待,否则它将继续
resetEvent.WaitOne();
}
}

public void暂停()
{
//取消设置重置事件,这将导致循环暂停
this .resetEvent.Reset();
Debug.WriteLine(Paused);
}

public void Resume()
{
//设置重置事件,这将导致循环继续
this.resetEvent.Set( );
Debug.WriteLine(Resumed);
}

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

//设置一个中止循环的标志
this.isRunning = false;

//设置我们当前暂停的事件
this.resetEvent.Set();

//等待线程完成
this.thread.Join();

Debug.WriteLine(已停止);
}
}





私人导航导航; 

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)
{
返回;
}

nav.Pause();
}

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

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();
}


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#

解决方案

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[^]


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();
}


这篇关于开始停止恢复线程C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆