一文熟练使用C#中的异步(async)编程实现WinForm UI界面进度条更新

目录

一、创作背景

二、WinForm程序遍历数据举例        

1、UI界面介绍

2、对应的代码

3、实际效果演示


一、创作背景

        芯片测试过程中,常常需要在for循环中进行各种测试条件的遍历,需要在UI界面上查看当前运行到什么条件和总的进度,想尝试直接在阻塞的线程中进行WinForm UI界面的进度更新是不现实的。C#中有同步、异步和多线程几种方式能实现上述功能,本文采用异步方式实现UI界面的进度条实时更新。

二、WinForm程序遍历数据举例        

1、UI界面介绍

        由于只是为了演示功能,界面很简介,主要有需要遍历条件的计数起始值、步进值和终止值,开始按键,以及需要显示当前进度信息的label1和进度条。

2、对应的代码

        

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

namespace Async_await_Method
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void buttonStart_Click(object sender, EventArgs e)
        {
            //在执行异步任务前先把UI界面控件的值赋值给局部自定义变量
            double CountStart = Convert.ToDouble(textBoxCountStart.Text);
            double CountStep = Convert.ToDouble(textBoxCountStep.Text);
            double CountStop = Convert.ToDouble(textBoxCountStop.Text);

            //根据起始值、步进和终止值创建一个lists
            int num = Convert.ToInt32(Math.Abs(CountStop - CountStart) / CountStep)+1; //计算lists长度
            double[] lists = new double[num]; //创建一个长度为num的lists
            for (int i = 0;i< num;i++) //根据起始值、步进和终止值生成对应元素放进lists中对应位置
            {
                if(CountStop> CountStart)
                {
                    lists[i] = CountStart + i*CountStep;
                }
                else
                {
                    lists[i] = CountStart - i * CountStep;
                }
            }

            progressBar1.Maximum = num; //设置进度条最大值为num

            await Task.Run(() => //更新UI界面
            {

                //采用委托的方式更新UI界面label1显示的字符串 
                if (label1.InvokeRequired) //label1委托请求
                {
                    while (!label1.IsHandleCreated)
                    {
                        //解决窗体关闭时出现“访问已释放句柄“的异常
                        if (label1.Disposing || label1.IsDisposed)
                            return;
                    }
                    Invoke(new Action(() => { label1.Text = "开始计数"; }));
                }
                else
                {
                    label1.Text = "开始计数";
                }

                //采用委托的方式设置buttonStart.Enabled = false,在此期间不允许再次点击该按键
                if (buttonStart.InvokeRequired) 
                {
                    while (!buttonStart.IsHandleCreated)
                    {
                        //解决窗体关闭时出现“访问已释放句柄“的异常
                        if (buttonStart.Disposing || buttonStart.IsDisposed)
                            return;
                    }
                    Invoke(new Action(() => { buttonStart.Enabled = false; }));
                }
                else
                {
                    buttonStart.Enabled = false;
                }

            });

            await Task.Run(async () =>
            {
                for (int i = 0;i< lists.Count(); i++)
                {
                    double bar1 = Math.Round((Convert.ToDouble(i + 1) / num)*100,3); //计算当前进度值,并保留3位有效数字

                    //采用委托的方式更新UI界面label1显示的字符串 
                    if (label1.InvokeRequired) //label1委托请求
                    {
                        while (!label1.IsHandleCreated)
                        {
                            //解决窗体关闭时出现“访问已释放句柄“的异常
                            if (label1.Disposing || label1.IsDisposed)
                                return;
                        }
                        Invoke(new Action(() => { label1.Text = "当前计数值:" + Convert.ToString(lists[i]) + ";计数进度为:" + Convert.ToString(bar1) + "%"; }));
                    }
                    else
                    {
                        label1.Text = "当前计数值:" + Convert.ToString(lists[i]) + ";计数进度为:" + Convert.ToString(bar1) + "%";
                    }

                    //采用委托的方式更新UI界面进度条显示的值
                    if (progressBar1.InvokeRequired) //progressBar1委托请求
                    {
                        while (!progressBar1.IsHandleCreated)
                        {
                            //解决窗体关闭时出现“访问已释放句柄“的异常
                            if (label1.Disposing || label1.IsDisposed)
                                return;
                        }
                        Invoke(new Action(() => { progressBar1.Value = Convert.ToInt32(i+1); }));
                    }
                    else
                    {
                        progressBar1.Value = Convert.ToInt32(i+1);
                    }
                    Thread.Sleep(1000); //延迟1000ms后计数值才加1
                }

            });

            await Task.Run(() =>
            {
                //采用委托的方式设置buttonStart.Enabled = true,允许再次点击该按键
                if (buttonStart.InvokeRequired)
                {
                    while (!buttonStart.IsHandleCreated)
                    {
                        //解决窗体关闭时出现“访问已释放句柄“的异常
                        if (buttonStart.Disposing || buttonStart.IsDisposed)
                            return;
                    }
                    Invoke(new Action(() => { buttonStart.Enabled = true; }));
                }
                else
                {
                    buttonStart.Enabled = true;
                }
            });
        }

    }
}

3、实际效果演示

使用C#中的异步(async)编程实现WinForm UI界面进度条更新

  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

零壹电子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值