Task暂停、继续、结束


Task实现暂停、继续、结束。

看到这个,有些童鞋可能会想到自动化设备上的“停止”,“开始”按钮。

勇哥要说的是,Task的暂停继续只是对于task的调度流程来说的,至于task内部跑的轴的运动逻辑来说,你还得有另外的办法让它同步暂停继续。

所以整机控制功能并不是靠线程的挂起与继续就那么容易实现的。



代码:


几点说明。

你可以在return那里下断点,程序最后会取消task的执行,就断在这里了。

因为这个是异步的代码,所以你只能这样检测取消功能了。


另外,对于WaitOne()之后的set和Reset,请记住口诀:  Reset暂停,Set启动


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication19
{
    class Program
    {
        static void Main(string[] args)
        {
            CancellationTokenSource tokenSource = new CancellationTokenSource();
            CancellationToken token = tokenSource.Token;
            ManualResetEvent resetEvent = new ManualResetEvent(true);

            Task task = new Task(async () =>
            {
                //输出i
                int i = 0;
 
                while (true)
                {
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }
                    resetEvent.WaitOne();
                    //do something
                    Console.WriteLine(i++);
                    await Task.Delay(100);
                }
               
            }, token);
            task.Start();

            //2秒后暂停
            Thread.Sleep(2000);
            resetEvent.Reset();
            Console.WriteLine("Reset");
            //2秒后启动
            Thread.Sleep(2000);
            resetEvent.Set();
            Console.WriteLine("Set");
            //2秒后暂停
            Thread.Sleep(2000);
            resetEvent.Reset();
            Console.WriteLine("Reset");
            tokenSource.Cancel();
            Console.ReadKey();
        }

        
    }
}


image.png


--------------------- 

作者:hackpig

来源:www.skcircle.com

版权声明:本文为博主原创文章,转载请附上博文链接!



本文出自勇哥的网站《少有人走的路》wwww.skcircle.com,转载请注明出处!讨论可扫码加群:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

会员中心
搜索
«    2024年5月    »
12345
6789101112
13141516171819
20212223242526
2728293031
网站分类
标签列表
最新留言
    热门文章 | 热评文章 | 随机文章
文章归档
友情链接
  • 订阅本站的 RSS 2.0 新闻聚合
  • 扫描加本站机器视觉QQ群,验证答案为:halcon勇哥的机器视觉
  • 点击查阅微信群二维码
  • 扫描加勇哥的非标自动化群,验证答案:C#/C++/VB勇哥的非标自动化群
  • 扫描加站长微信:站长微信:abc496103864
  • 扫描加站长QQ:
  • 扫描赞赏本站:
  • 留言板:

Powered By Z-BlogPHP 1.7.2

Copyright Your skcircle.com Rights Reserved.

鄂ICP备18008319号


站长QQ:496103864 微信:abc496103864