C# async/await 简单使用

async/await可以实现不阻塞主线程的情况下等待子线程的计算结果

private async void FormLoading_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;

            Task taskSetTxt = new Task(this.SetPBText);
            taskSetTxt.Start();

            Task<bool> taskMovPic = new Task<bool>(this.MovePic);
            taskMovPic.Start();

            //等待子线程的返回值,但不阻塞,主线程继续执行
            await taskMovPic;

            //当进度条加载到100%后返回值为true,这时隐藏加载窗体,显示客户端主窗体
            if (taskMovPic.Result)
            {
                this.Hide();
                m_formClient.Show();
            }


            /**************总结:利用async/await关键字可以在主线程中等待子线程的计算结果,重点在于在主线程等待的过程中不会阻塞***********/
        }
        public void SetPBText()
        {
            Graphics g = progressBar1.CreateGraphics();
            Font mf = new System.Drawing.Font("宋体", 10);
            Brush mb = System.Drawing.Brushes.White;
            Point mp = new System.Drawing.Point(progressBar1.Width / 2 - 60, progressBar1.Height / 2 - 8);
            while (true)
            {
                //this.progressBar1.PerformStep();
                g.DrawString(string.Format("Loading....{0}%", this.progressBar1.Value), mf, mb, mp);
                if (this.progressBar1.Value == 100)
                {
                    //m_bLoadIsOK = true;
                    //return;
                }
                //Thread.Sleep(1);
            }
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值