WinForm BackgroundWorker控件学习

1.新建一个窗体应用程序,选择.net framework4.7.2框架

2.从【工具箱】拖一个BackgroundWorker控件到窗体中,将其属性改成

WinForm BackgroundWorker控件学习_第1张图片

WorkerReportsProgress属性表示是否支持后台任务执行中随时报告进度

WorkerSupportsCancellation属性表示支持后台任务执行中随时取消执行

3.给窗体再拖一个【进度条ProgressBar】控件和一个【按钮Button】控件

WinForm BackgroundWorker控件学习_第2张图片

4.给【后台任务】和【按钮】控件添加事件,添加之前我们给窗体添加一个字符串msg

WinForm BackgroundWorker控件学习_第3张图片

WinForm BackgroundWorker控件学习_第4张图片

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.本程序执行时,点击按钮,如果任务正在执行,则会取消任务,否则就会执行任务。任务完成后,把msg内容替换到窗体的Text属性中,即可给客户展示此任务是已经完成还是被取消了。

6.运行截图

WinForm BackgroundWorker控件学习_第5张图片

 

WinForm BackgroundWorker控件学习_第6张图片

WinForm BackgroundWorker控件学习_第7张图片 

 

你可能感兴趣的:(C#,经验分享,学习,microsoft)