如何停止BackgroundWorker线程? [英] How do I stop a BackgroundWorker thread?

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

问题描述

大家好,

需要帮助以停止BackgroundWorker线程.我正在尝试停止后台工作者线程.这就是我在做什么:

Hi all,

Need help to stop the BackgroundWorker thread. I am trying to stop a background worker thread. This is what I am doing:

//On stop button click (UI layer):
if (backgroundWorker.IsBusy == true && backgroundWorker.WorkerSupportsCancellation == true) 
{     
    backgroundWorker.CancelAsync(); 
} 

//On DoWork event (UI layer):
if ((backgroundWorker.CancellationPending == true)) 
{      
    e.Cancel = true; 
} 
else 
{     
    //Function which progresses the progress bar is called      
    //here with its definition in business layer  
} 



一旦触发了DoWork事件并且我的程序控件位于业务层中定义的函数中,如何恢复为DoWork事件以设置'e.Cancel = true'?



Once the DoWork event is fired and my program control is in the function defined in Business layer, how do I revert back to the DoWork event to set ‘e.Cancel = true’?

推荐答案

我在这里有一个例子.在这个例子中说MyBusyObject类具有业务逻辑.

根据例子.问我是否有任何疑问

在业务逻辑代码中(在类文件中)...

I am having an example here. say in this example MyBusyObject class has the business logic.

Follow the example. Ask me if any doubt arises

In the business logic code (in class files)...

public interface IObservable
{
    void notify();
}
public interface IObserver
{
    void executeMessage(bool isStop);
}

public class MyBusyObject:IObserver
{
    int dummyValue;
    public bool isStop;
    public void busyFunction()
    {
        for(int i=0;i<1000000;i++){
            System.Threading.Thread.Sleep(1000);
            if (isStop == true) {
                //just for testing purpose
                System.Windows.Forms.MessageBox.Show("Loop stoped at " + i.ToString());
                //use return null if the function returns or whatever you may need to do
                break;
            }
            dummyValue = i;
        }
     }
    public void executeMessage(bool isStop)
    {
        this.isStop = isStop;
    }
}




在表单代码中...




In the form code...

public partial class Form1 : Form,IObservable
{

    private IList<IObserver> myObservers = new List<IObserver>();
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.WorkerSupportsCancellation = true;
        backgroundWorker1.RunWorkerAsync();
    }
    private void button2_Click(object sender, EventArgs e)
    {
        backgroundWorker1.CancelAsync();
        notify();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        MyBusyObject obj = new MyBusyObject();
        myObservers.Add(obj);
        for (int i = 0; i < 5; i++)
        {
            if ((backgroundWorker1.CancellationPending == true))
            {
                e.Cancel = true;
            }
            obj.busyFunction();
        }
    }

    public void notify()
    {
        foreach (IObserver observer in myObservers)
        {
            observer.executeMessage(true);
        }
    }


}


Button1用于启动,而button2用于停止.我正在从5个对象中调用busy函数,并通过按button2
来停止它
一旦您的繁忙函数返回,后台工作程序就会自动停止线程


Button1 is for start and button2 for stop. I am calling the busyfunction from 5 objects and stopping it by pressing the button2

Once your busy function returned, background worker stops thread automatically


AlbinAbel的解决方案是正确的,我只需更改busyFunction使其返回bool:如果busyFunction正常完成,如果false被取消,则可以从线程函数获取返回值,并将返回值分配给e.Cancel:

除了此解决方案之外,我还提醒您将e.Cancel设置为true不会使线程功能停止.仅当您处理RunWorkerCompleted事件时,此属性才有用.在这里,您可以检查线程功能是否已完全完成,是否已取消或由于未处理的异常而终止.
AlbinAbel''s solution is correct, I would just change the busyFunction to make it return a bool: true if busyFunction finished normally, false if it was cancelled, so you can get the return value back from the thread function and assign the return value to e.Cancel:

In addition to this solution, I remind you that setting e.Cancel to true will not make your thread function stop. This property is usefull only if you handle the RunWorkerCompleted event. Here you may check whether your thread function finished completely, or was canceled, or was terminated due to an unhandled exception.


这篇关于如何停止BackgroundWorker线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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