none
UWP异步 RRS feed

  • 问题

  • 我写了一个界面,包含一个ListBox和一个自定义的进度条,ListBox的item已经绑定。

    进度条包含一个Ellipse和TextBlock,当点击启动Button时,

    For循环,然后循环赋值给Ellipse的StrokeDashArray和TextBlock的Text(显示%),以及listbox循环添加item进去

    但是现在需要for循环完成才显示,我需要实时显示进度,需要用到异步,但是不太懂,哪位老师给讲讲。谢谢

     ObservableCollection<da> cs = new ObservableCollection<da>();

     private async void js_Click(object sender, RoutedEventArgs e)
            {

       for (int i = 0; i < 1000000; i ++)
           {

      cs.Add(new da{ LC =i});

      lb.ItemsSource = cs;

     double  u =i/(1000000/100);

      wz.Text=u..ToString() + "%";

    YH.StrokeDashArray =new DoubleCollection() { u / 100 * 122.52 };

            }

           }

    2016年4月21日 1:39

答案

  • 用BackgroundWorker

    BackgroundWorker bgWorker = new BackgroundWorker();
            public MainWindow()
            {
                InitializeComponent();
                bgWorker.WorkerReportsProgress = true;
                bgWorker.DoWork += DoWork_Handler;
                bgWorker.ProgressChanged += ProgressChanged_Handler;
                if (!bgWorker.IsBusy)
                {
                    bgWorker.RunWorkerAsync();//开始运行DoWork_Handler里的功能
                }

            }

            private void DoWork_Handler(object sender, DoWorkEventArgs args)
            {
                BackgroundWorker worker = sender as BackgroundWorker;
                for (int i = 1; i <= 100; i++)
                {
                    //数据处理
                    worker.ReportProgress(i);
                    Thread.Sleep(50);
                }
            }

            private void ProgressChanged_Handler(object sender, ProgressChangedEventArgs args)
            {
                //这里更新ui
                s.Value = (double)args.ProgressPercentage;
            }

    2016年4月22日 4:27