隐藏

C# 实时更新进度 不卡死界面 BackgroundWorker

发布:2023/3/20 0:23:58作者:管理员 来源:本站 浏览次数:454



一、封装可重用类



  public class Async

   {

       protected BackgroundWorker bgWorker = new BackgroundWorker();

       /**

        * 业务方法

        */

       public static Async DoWork(Action<object?, DoWorkEventArgs> DoWork) {

           Async async = new();

           async.bgWorker.DoWork += new DoWorkEventHandler(DoWork);

           return async;

       }

       /**

       * 进度状态

       */

       public Async ProgressChanged(Action<object?, ProgressChangedEventArgs> ProgessChanged)

       {

           bgWorker.WorkerReportsProgress = true;

           bgWorker.ProgressChanged += new ProgressChangedEventHandler(ProgessChanged);

           return this;

       }

       /**

        * 结束状态

        */

       public Async RunWorkerCompleted(Action<object?, RunWorkerCompletedEventArgs> WorkerCompleted)

       {

           bgWorker.WorkerSupportsCancellation = true;

           bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(WorkerCompleted);

           return this;

       }

       /**

        * 启动

        */

       public BackgroundWorker Start(object? o) {

           if (bgWorker.IsBusy)

               return bgWorker;

           bgWorker.RunWorkerAsync(o);

           return bgWorker;

       }


   }






二、测试


1、不卡死界面测试


private void StartUpdateClick(object sender, RoutedEventArgs e){

 bgWorker = Async.DoWork(delegate (object? sender,DoWorkEventArgs e){

   for (int i=1;i<=100;i++) {Thread.Sleep(1000);}

}).Start(this);          

}




2、更新进度测试



private BackgroundWorker bgWorker;        

private void StartClick(object sender, RoutedEventArgs e)

       {

           bgWorker = Async.DoWork(delegate (object? sender, DoWorkEventArgs e){

               for (int i=1;i<=100;i++) {

                   bgWorker.ReportProgress(i);

               }

           }).ProgressChanged(delegate (object? sender, ProgressChangedEventArgs e) {

               ProgressBarBox.Value = e.ProgressPercentage;

           }).RunWorkerCompleted(delegate (object? sender, RunWorkerCompletedEventArgs e) {

               if (e.Error != null)

               {

                   MessageBox.Show(e.Error.ToString());

                   return;

               }

               if (!e.Cancelled)

               {

                   FinishBox.Visibility = Visibility.Visible;

                   QuitBox.Visibility = Visibility.Hidden;

               }

               else

               {

                   MessageBox.Show("处理终止!");

               }

           }).Start(this);

       }