WinForm BackgroundWorker control learning

1. Create a new form application and select the .net framework4.7.2 framework

2. Drag a BackgroundWorker control from [Toolbox] to the form, and change its property to

The WorkerReportsProgress attribute indicates whether to support background task execution to report progress at any time

The WorkerSupportsCancellation attribute indicates that it supports background task execution at any time during execution

3. Drag another [Progress Bar] control and a [Button Button] control to the form

4. Add events to the [Background Task] and [Button] controls. Before adding, we add a string msg to the form

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WFXX
{
    public partial class BackgroundWorkerForm : Form
    {
        private string msg = "";

        public BackgroundWorkerForm()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, EventArgs e)
        {
            if (backgroundWorker.IsBusy)
            {
                backgroundWorker.CancelAsync();
            }
            else
            {
                Text = "";
                backgroundWorker.RunWorkerAsync();
            }
        }

        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 1; i <= 100; i++)
            {
                if (backgroundWorker.CancellationPending)
                {
                    e.Cancel = true;
                    msg = "任务被取消";
                    return;
                }
                else
                {
                    System.Threading.Thread.Sleep(50);
                    backgroundWorker.ReportProgress(i);
                }
            }
            msg = "任务已完成";
        }

        private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar.Value = e.ProgressPercentage;
        }

        private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Text = msg;
        }
    }
}

5. When the program is executed, click the button, if the task is being executed, the task will be canceled, otherwise the task will be executed. After the task is completed, replace the msg content into the Text property of the form to show the client whether the task has been completed or canceled.

6. Run the screenshot

 

 

 

Guess you like

Origin blog.csdn.net/qq_36694133/article/details/128557892