停止后台工作者 [英] Stopping background worker

查看:92
本文介绍了停止后台工作者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序使用后台工作程序在循环中执行一些工作.我有它,以便在每次循环迭代时,它检查取消挂起是否为真,如果是,则中断循环.好的,一旦循环的当前迭代完成,我的应用程序便停止处理.问题是我认为后台工作程序仍在运行-如果单击该按钮再次开始处理,则会收到错误消息,表示后台工作程序很忙.

My app uses background worker to go do some work inside a loop. I have it so that at each loop iteration, it checks if cancellation pending is true and if it is, breaks out the loop. All OK, my app stops processing once it is finished the current iteration of the loop. The problem is that I think the background worker is still running - if I click the button to start processing again, I get an error saying the background worker is busy.

我本来打算处理该工作程序的,但是它会在表单运行时创建,因此,如果我处理它,就无法再次开始工作了.我真正想做的就是告诉后台工作人员它已经完成,如果我单击停止处理"按钮,那么当我单击开始"按钮时它就准备好再次开始处理!

I was going to dispose of the worker but then it is created when the form runs and so if I dispose of it, it is not there to start doing work again. What I really want to do is tell the background worker that it is complete, if I click a 'stop processing' button, so it is ready to start processing again when I click the start button!

我要尝试这个:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
{ 
    while (!backgroundWorker1.CancellationPending) 
    {
        // Start processing in a background thread so the GUI remains responsive,
        // pass in the name of the text file produced by 
        // PFDR FilenameLogic(txtLetterType.Text); 
    } 
}

推荐答案

答案与Marc Gravell相同,但您似乎不遵循.

Same answer as Marc Gravell but you don't seem to follow.

您是否设置e.cancel = true?

Are you setting e.cancel = true?

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            for (int i = 1; i <= 10; i++)
            {
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    // Perform a time consuming operation and report progress.
                    System.Threading.Thread.Sleep(500);
                    worker.ReportProgress(i * 10);
                }
            }
        }

这篇关于停止后台工作者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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