TASK的开始与暂停


namespace WpfApplication1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        // create the cancellation token source  
        private CancellationTokenSource TokenSource = new CancellationTokenSource();
        private Task CurrentTask;
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            // create the cancellation token  
            CancellationToken token = TokenSource.Token;
            // create the task  

            CurrentTask = new Task(() =>
            {
                for (int i = 0; i < int.MaxValue; i++)
                {
                    if (token.IsCancellationRequested)
                    {
                        Debug.WriteLine("Task cancel detected");
                        break;
                        //throw new OperationCanceledException(token);
                    }
                    else
                    {
                        Debug.WriteLine("Int value {0}", i);
                    }
                }
            }, token);


            // start the task  
            CurrentTask.Start();
        }

        private void btnStop_Click(object sender, RoutedEventArgs e)
        {
            if (CurrentTask != null)
            {
                if (CurrentTask.Status == TaskStatus.Running) { }
                {
                    TokenSource.Cancel();
                    Debug.WriteLine("Task cancel");
                }
            }
        }
    }
}

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM