• sync 异步编程


     1 using System;
     2 using System.Net;
     3 using System.Threading;
     4 using System.Threading.Tasks;
     5 
     6 
     7 namespace ConsoleApp1
     8 {
     9     class Program
    10     {
    11         static void Main(string[] args)
    12         {
    13             Console.WriteLine($"Main Start...{System.Threading.Thread.CurrentThread.GetHashCode()}");
    14 
    15             var rst = DisplayValueAsync();
    16 
    17             Console.WriteLine($"Main do some thing End...{System.Threading.Thread.CurrentThread.GetHashCode()}");
    18 
    19             Console.WriteLine($"Sub1  End...values is {rst.Result} {System.Threading.Thread.CurrentThread.GetHashCode()}");
    20 
    21             Console.Read();
    22 
    23 
    24         }
    25 
    26 
    27          public static async Task<int> DisplayValueAsync()
    28         {
    29             Console.WriteLine($"Sub call...{System.Threading.Thread.CurrentThread.GetHashCode()}");
    30 
    31            var rst= await Task<int>.Run(()=> {
    32 
    33                System.Threading.Thread.Sleep(2000);
    34 
    35                Console.WriteLine($"Sub exec...{System.Threading.Thread.CurrentThread.GetHashCode()}");
    36 
    37 
    38                var random = new Random();
    39                return random.Next(1,1000);
    40 
    41             });
    42 
    43             return rst;
    44 
    45         }
    46 
    47 
    48 
    49     }
    50 
    51 }
    View Code

    https://www.cnblogs.com/yaopengfei/p/9249390.html

    执行异步方法的时候有几个注意事项

    1.sync与await要成对出现,异步方法只能有3个返回值 (void Task 与 Task<T>)

    2.异步方法内要自行通过task.run开辟新的线程出来

    3.主线程通过调用异步方法task.Resutl来获取线程结果,此时也会阻塞线程等待结果

  • 相关阅读:
    NSDate相差8小时
    IOS 多播委托(GCDMulticastDelegate)
    点云、矢量、三维模型数据的平移
    mongodb集群搭建过程记录
    mongodb 使用常见问题汇总(主要是集群搭建)
    安装py3ditles中遇到的问题
    linux常见问题集锦
    Ubuntu18.04 + win10双系统下时间问题
    Frank Dellaert Slam Speech 20190708
    计算机系统基础学习笔记及博客
  • 原文地址:https://www.cnblogs.com/xinzhyu/p/11568805.html
Copyright © 2020-2023  润新知