• C#基础 依赖BackgroundWorker类多线程实现进度条 代码示例


        class Program
        {
            static BackgroundWorker bw;
    
            static void Main(string[] args)
            {
                bw = new BackgroundWorker
                {
                    WorkerReportsProgress = true,
                    WorkerSupportsCancellation = true
                };
    
                bw.DoWork += Bw_DoWork;
                bw.ProgressChanged += Bw_ProgressChanged;
                bw.RunWorkerCompleted += Bw_RunWorkerCompleted;
                //开始工作(新线程)
                bw.RunWorkerAsync("Hello");
    
                Console.ReadLine();
                if (bw.IsBusy)
                    bw.CancelAsync();
                Console.ReadLine();
            }
    
            //工作进度完成事件
            private static void Bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
            {
                if (e.Cancelled)
                {
                    Console.WriteLine("You canclled!");
                }
                else if (e.Error != null)
                {
                    Console.WriteLine($"Error:{e.Error}");
                }
                else
                    Console.WriteLine($"Completed-{e.Result}");
            }
    
            //进度改变后事件
            private static void Bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
            {
                Console.WriteLine($"Reached {e.ProgressPercentage}%");
            }
    
            private static void Bw_DoWork(object sender, DoWorkEventArgs e)
            {
                while (true)
                {
                    Console.WriteLine("Press Enter in the next 5 seconds to cancel");
                    for (int i = 0; i <= 100; i += 20)
                    {
                        //若是取消了
                        if (bw.CancellationPending)
                        {
                            e.Cancel = true;
                            return;
                        }
                        //报告进度变化,引发进度改变事件
                        bw.ReportProgress(i);
                        Thread.Sleep(1000);
                    }
                    e.Result = 123;
                }
            }
        }
  • 相关阅读:
    java-String类
    多线程的细节
    java-多线程的练习----妖,等待唤醒,代码重构,lock到condition
    javascript函数的声明和调用
    表单
    java-多线程的入门_进阶总结
    uboot命令
    u-boot移植 III
    u-boot移植 II
    汇编词典
  • 原文地址:https://www.cnblogs.com/vsSure/p/7965473.html
Copyright © 2020-2023  润新知