可取消可報告進度的Task

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace WpfApp2
{
    public partial class MainWindow : Window
    {
        CancellationTokenSource Cts = new CancellationTokenSource();
        public MainWindow()
        {
            Person p = new Person();
            p.Do(Cts.Token, new Progress<int>((xpp)=>label.Content=xpp));
        }

        /// <summary>
        /// 按鈕按下事件處理函數
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Cts.Cancel();
        }
    }


    public class Person
    {
        public string name { get; set; }
        public string age { get; set; }
        public int length { get; set; }
        public void Do(CancellationToken token, IProgress<int> progress)
        {
            Action action = new Action(() =>
            {
                try
                {
                    for (int i = 0; i < 30; i++)
                    {
                        Thread.Sleep(1000);
                        //報告進度
                        progress.Report(i);
                        //若是用戶執行CancellationTokenSource.Cancel()方法就拋出異常
                        //從而達到取消線程操做
                        token.ThrowIfCancellationRequested();
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("取消線程執行");
                }
            });

            Task task = new Task(action,token);
            task.Start();
        }
    }
}


這裏有一點須要說明,那就是Progress其實是跨線程修改控件,去system.Progress源碼中找到Report的源碼中調用了OnReport函數,以下圖:
m_synchronizationContext變量是個SynchronizationContext類型,用於線程間通訊。
c#

相關文章
相關標籤/搜索