zoukankan      html  css  js  c++  java
  • winform中执行任务,解决未响应界面

      private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
            {
                var count = (int)e.Argument;
                for (int i = 1; i <= count; i++)
                {
                    if (backgroundWorker1.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }

                    //if (i == 2)
                    //    throw new Exception("出错啦!");

                    backgroundWorker1.ReportProgress(i);
                    //任务             
                    Thread.Sleep(500);//模拟耗时的任务              
                }
            }

            private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
            {
                toolStripProgressBar1.Value = e.ProgressPercentage;
                toolStripStatusLabel1.Text = DateTime.Now.ToString();
            }
            //更新UI,异常处理
            private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
            {
                if (e.Cancelled)
                    toolStripStatusLabel1.Text += "任务取消。";
                else if (e.Error != null)
                    toolStripStatusLabel1.Text += "出现异常: " + e.Error;
                else
                    toolStripStatusLabel1.Text += "任务完成。 ";
            }

            private void button1_Click(object sender, EventArgs e)
            {
                if (!backgroundWorker1.IsBusy)
                {
                    toolStripProgressBar1.Value = 0;
                    toolStripProgressBar1.Maximum = 100;

                    toolStripStatusLabel1.Text = "任务开始...";
                    //标记
                    backgroundWorker1.RunWorkerAsync(100);
                }
                else
                {
                    MessageBox.Show("正在进行异步操作.");
                }
            }

            private void button2_Click(object sender, EventArgs e)
            {
                backgroundWorker1.CancelAsync();
            }

  • 相关阅读:
    Eclipse中创建标准web工程以及标准目录结构说明
    log4j配置说明
    常用的Eclilpse插件列表以及安装方式总结
    Eclipse插件安装总结
    eclipse中加放js文件报js语法错误解决办法
    如何在Eclipse中配置Tomcat服务器
    webpack的单vue组件(.vue)加载sass配置
    总结自己常用的几种居中方式
    两个正则坑
    CSS拾遗(二)
  • 原文地址:https://www.cnblogs.com/iframe/p/5486363.html
Copyright © 2011-2022 走看看