BackgroendWorker通常用在背景執行程序, 因此可以讓程式同時執行多執行緒.

簡單說,你可以同時計算A資料及瀏覽B資料,並不用等待A資料處理完才能去瀏覽B資料.

另外BackgroendWorker可以透過事件回傳目前執行的狀況, 即目前處理的進度.


[屬性]

名稱

描述

CancellationPending

取得值,指出應用程式是否已要求取消背景作業。

IsBusy

取得值,指出是否 BackgroundWorker 執行非同步作業。

WorkerReportsProgress

取得或設定值,指出是否 BackgroundWorker 可以報告進度更新。

WorkerSupportsCancellation

取得或設定值,指出是否 BackgroundWorker 支援非同步取消作業。

 

[方法]

名稱

描述

CancelAsync()

要求取消暫止的背景作業。

RunWorkerAsync()

開始執行背景作業。引發DoWork事件

ReportProgress(Int32)

引發 ProgressChanged 事件。

 

[事件]

名稱

描述

DoWork

當 RunWorkerAsync 呼叫後會引發此事件

ProgressChanged

當 ReportProgress 呼叫後引發此事件

RunWorkerCompleted

發生於背景作業已完成、 已取消,或引發例外狀況。

[範例]

-----------------執行背景程序------------------------------------

        private void butTest_Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

//-----------------將執行的背景程序------------------------------------

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            for(int i =0; i<=100; i++)
            {
                backgroundWorker1.ReportProgress(i); //呼叫狀態列並傳遞參數
                System.Threading.Thread.Sleep(100);  //暫停程序100ms
            }

//-----------------背景程序處理中(被呼叫才會有動作)------------------------------------

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.progressBar1.Value = e.ProgressPercentage; //設定
        }

//-----------------背景程序處理完成------------------------------------
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            txtState.Text="執行完成"; 
        }

對控制項呼叫需要使用安全執行緒

不可採用非安全執行緒

在DoWork中不能呼叫或設定任何控制項,否則會發生錯誤或不正常執行.

1.在DoWork事件中設定progressBar1.Value的值

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            for(int i =0;i<=100;i++)
            {
                backgroundWorker1.ReportProgress(i);
                System.Threading.Thread.Sleep(100);
                this.progressBar1.Value = i;
            }
        }

2.在DoWork事件中呼叫副程式,副程式再去呼叫或設定控制項.

因此只能在ProgressChanged事件中設定progressBar1.Value的值或RunWorkerCompleted呼叫及設定控制項.

 

如果是屬於系統控制項類別都不行

System.ComponentModel.Component

如果是HttpWebRequest這類則沒問題

System.Net.HttpWebRequest

 

 

arrow
arrow
    全站熱搜

    門外漢 發表在 痞客邦 留言(0) 人氣()