可以重用backgroundworker对象吗?

可以重用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;
    }