TASK的开始与暂停

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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");
                }
            }
        }
    }
}

  

posted @   怒放生命  阅读(1954)  评论(0编辑  收藏  举报
编辑推荐:
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
阅读排行:
· 手把手教你在本地部署DeepSeek R1,搭建web-ui ,建议收藏!
· 新年开篇:在本地部署DeepSeek大模型实现联网增强的AI应用
· Janus Pro:DeepSeek 开源革新,多模态 AI 的未来
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(三):用.NET IoT库
· 【非技术】说说2024年我都干了些啥
点击右上角即可分享
微信分享提示