• C# 异步的简单用法


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace ConsoleApp3
    {
        class Class3
        {
            CancellationTokenSource source = new CancellationTokenSource();
            internal void Run()
            {
                
                CancellationToken token = source.Token;
                TaskFactory factory = new TaskFactory(token);
                //创建一个 异步
                Task<string> task = factory.StartNew(TestTaskEvent1, token);
                // task.Start();
                Thread.Sleep(15000);
                //不取消 此函数会一直循环
                source.Cancel();
                //Console.WriteLine(task.Result);
                Console.WriteLine("aaaer");
                source.Dispose();
            }
    
            private string TestTaskEvent1(object obj)
            {
                while (!source.IsCancellationRequested)
                {
                    Thread.Sleep(100);
                }
                //for (int i = 1; i <= 3; ++i)
                //{
                //    Thread.Sleep(1000);
    
                //}
    
                Console.WriteLine("event over");
                return "a";
            }
    
            internal void Run1()
            {
                CancellationTokenSource source = new CancellationTokenSource();
                CancellationToken token = source.Token;
    
                Task<string> task = new Task<string>(TestTaskEvent, source, token);
                task.Start();
                Thread.Sleep(1500);
                source.Cancel();
                Console.WriteLine(task.Result);
                //此处会等待Result执行完毕后再执行
                Console.WriteLine("aaa");
            }
            string TestTaskEvent(object obj)
            {
               
                for (int i = 1; i <= 3; ++i)
                {
                    Thread.Sleep(1000);
         
                }
    
                return "a";
            }
        }
    }
    

      

  • 相关阅读:
    vue与laravel
    php artisan 命令
    HTTP 状态码
    PhpStorm提高效率的使用方法及设置
    好RESTful API的设计原则
    laravel 入门基础之安装
    c++ sizeof(字符数组)
    new delete/delete[] 测试
    linux g++ 查找动态链接库
    linux下定时器耗时研究
  • 原文地址:https://www.cnblogs.com/z45281625/p/11190226.html
Copyright © 2020-2023  润新知