C#异步编程 Task.Run 报告进度

 

 

 CancellationTokenSource cts;
        private async void start_click(object sender, RoutedEventArgs e)
        {
            this.prg.Maximum = 100;
            this.prg.Value = 0;
            cts = new CancellationTokenSource();
            CancellationToken ct = cts.Token;
            var pp = new Progress(value => this.prg.Value = value);
            //var pp = new Progress();
            //pp.ProgressChanged += (s, n) =>
            //{
            //    this.prg.Value = n;
            //};
            var tt = Task.Run(
                () =>MyThreadAsync(pp,ct,100) 
                );
            try
            {
                await tt;
                if (tt.Exception==null)
                {
                    MessageBox.Show("任务完成");

                }
            }
            catch
            {
                MessageBox.Show("发生异常");
            }
        }
        public void MyThreadAsync(IProgress progress,CancellationToken tk,int delay)
        {
            int p = 0;
            while (p < 100) //&& tk.IsCancellationRequested==false
            {
                p += 1;
                Thread.Sleep(delay);
                progress.Report(p);
                tk.ThrowIfCancellationRequested(); //它会终止任务并且返回catch语句块里面
            }
        }

        private void stop_click(object sender, RoutedEventArgs e)
        {
            cts.Cancel();
        }

 

你可能感兴趣的:(C#)