zoukankan      html  css  js  c++  java
  • WinForm 进度条

    目标:MyForm上有个Button,按下后会执行Task,Task会返回中间结果,然后在Label上实时显示中间结果。

    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    public partial class MyForm : Form
    {
    
        //1)Label的更新
        private readonly object statusLabel = new object();
        private void UpdateLabel(string txt)
        {
            lock (statusLabel)
            {
                this.Label1.Text = txt;
            }
        }
    
        //2)Task定义
        Random rand = new Random();
        public void SearchFilesInTarget(IProgress<string> onSearchingFile) 
        {
            while (true)
            {
                string result = "file_name" + rand.Next();
                onSearchingFile.Report(result);
            }
        }
    
        //3)按钮按下
        private readonly CancellationTokenSource cancelToken = new CancellationTokenSource();
        private void SearchStart_Click(object sender, EventArgs e)
        {
            var onSearchingFile = new Progress<string>(txt => this.BeginInvoke(updateLabel, "Searching..." + txt));
            Task myTask = Task.Factory.StartNew(() => SearchFilesInTarget(onSearchingFile), cancelToken.Token);
        }
    
    
        //4)构造BeginInvoke的参数
        public delegate void DelegateUpdateLabel(string file);
        private DelegateUpdateLabel updateLabel;
    
        public MyForm()
        {
            updateLabel = new DelegateUpdateLabel(UpdateLabel);
        }
    }
    

      

  • 相关阅读:
    PAT Advanced 1073 Scientific Notation (20 分)
    PAT Advanced 1071 Speech Patterns (25 分)
    C++ 正则查找
    PAT Advanced 1022 Digital Library (30 分)
    Linux文件系统及常用命令
    Elasticsearch常用查询
    Sublime Text3 快捷键
    Lua函数
    线程池
    Jdk8新特性之Base64
  • 原文地址:https://www.cnblogs.com/wyvern0618/p/8926255.html
Copyright © 2011-2022 走看看