博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
用Thread和Task+async+awati实现WinFrom里面的进度条
阅读量:4587 次
发布时间:2019-06-09

本文共 2264 字,大约阅读时间需要 7 分钟。

新建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
updateUi = new Action
(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 }}

 

转载于:https://www.cnblogs.com/dacaba/p/10310790.html

你可能感兴趣的文章
iOS runtime实用篇--和常见崩溃say good-bye!
查看>>
细说Cookie
查看>>
Javascript 第二章
查看>>
几个常用算法及反射+多线程调用
查看>>
ubuntu12.04 上面配置blogilo的博客园客户端的步骤
查看>>
Codeforces Gym101170I:Iron and Coal(建多幅图+多次BFS)***
查看>>
Python杂俎 —— 自动压缩指定格式文件&自动删除
查看>>
2017年01月。。
查看>>
ASP.NET的路由系统:根据路由规则生成URL
查看>>
ASP.NET Core Razor 视图起始页 - ASP.NET Core 基础教程 - 简单教程,简单编程
查看>>
从PRISM开始学WPF(四)Prism-Module?
查看>>
解决session阻塞的问题
查看>>
SQL Server 触发器
查看>>
css优先级计算规则
查看>>
Asp.Net Web API 2第十五课——Model Validation(模型验证)
查看>>
Silverlight 4 MVVM开发方式(三)动态换皮
查看>>
ExtJs中OA管理中组织和用户关系左右选择组件的运用
查看>>
【原创】关于高度自适应问题
查看>>
Tomcat JMX
查看>>
2019 年,容器技术生态会发生些什么?
查看>>