欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用Thread和Task实现WinFrom里面的进度条

程序员文章站 2022-03-01 23:15:09
...
新建WinFrom项目,在界面上添加两个按钮
分别用Thread和Task实现进度条效果
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

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

        //普通Thread实现进度条
        private void button1_Click(object sender, EventArgs e)
        {
            Console.WriteLine("主线程开始");

            new Thread(DoProcessing).Start(); //没有使用线程池,每次调用都开启新线程
            //ThreadPool.QueueUserWorkItem(DoProcessing);//使用线程池,重复开启的时候回去线程池拿空闲的线程

            Console.WriteLine("主线程结束");
        }

        //在方法上加上 async 
        private async void button2_Click(object sender, EventArgs e)
        {
            await UpdateUi2();

            //async.await的语法糖为我们带来了更好的异步编程体验
        }


        #region Thread

        void UpdateUi(int percent)
        {
            //UI操作
            button1.Text = string.Format("{0}%", percent);
        }

        void DoProcessing(object obj)
        {
            for (int i = 0; i <= 5; ++i)
            {
                Thread.Sleep(500);
                Console.WriteLine("---------- " + i);
                Action<int> updateUi = new Action<int>(UpdateUi);
                this.Invoke(updateUi, i);
            }
        }

        #endregion


        #region task,async,await

        private static int _percent = 0;

        int DoProcessing2()
        {
            Console.WriteLine("Thread id in DoProcessing: {0}", Thread.CurrentThread.ManagedThreadId);
            Thread.Sleep(500);
            return ++_percent;
        }

        async Task UpdateUi2()
        {
            _percent = 0;
            button1.Text = string.Format("{0}%", 0);
            while (_percent < 5)
            {
                //await起到释放主线程的作用
                int percent = await Task.Run(() => DoProcessing2());
                //在子线程处理完成后,又请求主线程继续下面的代码,下面的代码相当于Thread的回调
                button2.Text = string.Format("{0}%", percent);
            }
        }

        #endregion


        #region 参考

        private void button3_Click(object sender, EventArgs e)
        {
            Thread.Sleep(3000); //堵塞主线程
            button1.Text = string.Format("99%");
        }

        #endregion
    }
}
相关标签: thread