zoukankan      html  css  js  c++  java
  • C# 实践 3 task 关键字

    参考:

    https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.tasks.task?view=netframework-4.8#definition

    Task 类表示不返回值并且通常以异步方式执行的单个操作

    来自参考的示例代码:

    using System;
    using System.Threading;
    using System.Threading.Tasks;
    
    class Example
    {
        static void Main()
        {
            Action<object> action = (object obj) =>
                                    {
                                       Console.WriteLine("Task={0}, obj={1}, Thread={2}",
                                       Task.CurrentId, obj,
                                       Thread.CurrentThread.ManagedThreadId);
                                    };
    
            // Create a task but do not start it.
            Task t1 = new Task(action, "alpha");
    
            // Construct a started task
            Task t2 = Task.Factory.StartNew(action, "beta");
            // Block the main thread to demonstrate that t2 is executing
            t2.Wait();
    
            // Launch t1 
            t1.Start();
            Console.WriteLine("t1 has been launched. (Main Thread={0})",
                              Thread.CurrentThread.ManagedThreadId);
            // Wait for the task to finish.
            t1.Wait();
    
            // Construct a started task using Task.Run.
            String taskData = "delta";
            Task t3 = Task.Run( () => {Console.WriteLine("Task={0}, obj={1}, Thread={2}",
                                                         Task.CurrentId, taskData,
                                                          Thread.CurrentThread.ManagedThreadId);
                                       });
            // Wait for the task to finish.
            t3.Wait();
    
            // Construct an unstarted task
            Task t4 = new Task(action, "gamma");
            // Run it synchronously
            t4.RunSynchronously();
            // Although the task was run synchronously, it is a good practice
            // to wait for it in the event exceptions were thrown by the task.
            t4.Wait();
        }
    }
    // The example displays output like the following:
    //       Task=1, obj=beta, Thread=3
    //       t1 has been launched. (Main Thread=1)
    //       Task=2, obj=alpha, Thread=4
    //       Task=3, obj=delta, Thread=3
    //       Task=4, obj=gamma, Thread=1
    

      

  • 相关阅读:
    【STM32F429】第4章 RTX5操作系统移植(MDK AC5)
    【STM32F407】第4章 RTX5操作系统移植(MDK AC5)
    【STM32H7】第3章 RTX5操作系统介绍
    【STM32F429】第3章 RTX5操作系统介绍
    【STM32F407】第3章 RTX5操作系统介绍
    【STM32H7】第2章 初学RTX5准备工作
    【STM32F429】第2章 初学RTX5准备工作
    Hystrix解析(一)
    Eureka源码解析(五)
    Eureka源码分析(四)
  • 原文地址:https://www.cnblogs.com/alexYuin/p/12397678.html
Copyright © 2011-2022 走看看