可以重用backgroundworker对象吗? [英] Is The reuse of the backgroundworker object possible?

查看:77
本文介绍了可以重用backgroundworker对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个刷新"按钮,每次单击它时,我都希望我的backgroundworker对象起作用.

I have a button "refresh" which every time i click on it i want my backgroundworker object to work.

我使用

if (main_news_back_worker.IsBusy != true)
        {
            // Start the asynchronous operation.

            main_news_back_worker.RunWorkerAsync();
        }
private void main_news_back_worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        show_system_urls(urls);
        displayNewMes(newMes, newStock, newSource);
        displayOldMes(oldMes, oldStock);

    }

我第一次使用backgroundworker可以很好地工作,并且还可以进入RunWorkerCompleted并完成他的工作. 但是第二次我尝试运行该对象时,该对象的is_busy属性为'true',并且我无法再次运行该对象...

The first time i use the backgroundworker it work good and also get to the RunWorkerCompleted and do his work. But the second time i try to run the object the is_busy property of the object is 'true' and i cant run the object again...

每次运行我都需要创建一个新的背景工作人员吗?我该怎么做? 谢谢.

Do i need to create a new backgroundworker every time i want to run it? how do i do it? Thanks.

推荐答案

是的,没问题.但是,您必须确保BGW忙时用户不能再次单击该按钮.通过设置Enabled属性可以轻松完成,停止按钮动作并向用户提供出色的视觉反馈.尝试以下示例:

Yes, no problem. You will however have to make sure that the user cannot click the button again while the BGW is busy. Easily done by setting the Enabled property, stops the button action and provides excellent visual feedback to the user. Try this for example:

    private void button1_Click(object sender, EventArgs e) {
        button1.Enabled = false;
        backgroundWorker1.RunWorkerAsync();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
        System.Threading.Thread.Sleep(2000);
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
        button1.Enabled = true;
    }

这篇关于可以重用backgroundworker对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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