星期六, 2月 18, 2017

[C#] BackgroundWorker 範例2

閱讀該篇 MSDN 文章 - BackgroundWorker 類別 並記錄,該文章是利用迴圈和 Tread.Sleep 來產生耗時操作,藉此來學習 BackgroundWorker

WinForm layout

[C#] BackgroundWorker 簡易範例-1


using System.Threading

namespace BackgroundWorkerSimple
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.WorkerSupportsCancellation = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            backgroundWorker1.DoWork += BackgroundWorker1_DoWork;
            backgroundWorker1.ProgressChanged += BackgroundWorker1_ProgressChanged;
            backgroundWorker1.RunWorkerCompleted += BackgroundWorker1_RunWorkerCompleted;
        }

        private void BackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled == true)
                lblResult.Text = "取消";
            else if (e.Error != null)
                lblResult.Text = "錯誤訊息: " + e.Error.Message;
            else
                lblResult.Text = "完成";
        }

        private void BackgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            lblResult.Text = $"已完成進度:{e.ProgressPercentage}%";
        }

        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;
                }

                // Perform a time consuming operation and report progress.
                Thread.Sleep(500);
                worker.ReportProgress(i * 10);
            }
        }

        private void btnStartAsync_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy == true) return;
            // Start the asynchronous operation.
            backgroundWorker1.RunWorkerAsync();
        }

        private void btnCancelAsync_Click(object sender, EventArgs e)
        {
            // WorkerSupportsCancellation 屬性為 true,才可以執行 CancelAsync method
            if (backgroundWorker1.WorkerSupportsCancellation == false) return;
            // Cancel the asynchronous operation.
            backgroundWorker1.CancelAsync();
        }
    }
}

執行結果

[C#] BackgroundWorker 簡易範例-2

[C#] BackgroundWorker 簡易範例-4

[C#] BackgroundWorker 簡易範例-3

沒有留言:

張貼留言