zoukankan      html  css  js  c++  java
  • 使用await和async异步编程

     class Program
        {
            private static readonly Stopwatch Watch = new Stopwatch();
            static void Main(string[] args)
            {
                Watch.Start();

                Compute();
                GetRandom();

                Watch.Stop();
                Console.ReadKey();
            }

            private static async void Compute()
            {
                var a = await GetSum();//任务开始后,直接继续执行下一步
                Console.WriteLine(Watch.ElapsedMilliseconds + "异步方法完成结果:" + a);//直到调用a时候,如果任务未完成就会等待任务完成。
            }

            private static Task<long> GetSum()
            {

                var random = new Random();
                var length = random.Next(10000, 100000);
                long result = 0;
                var task = new Task<long>(() =>
                {
                    for (int i = 0; i < length; i++)
                    {
                        result += i;
                    };
                    return result;
                });

                task.Start();
                return task;

            }

            private static void GetRandom()
            {
                var random = new Random();
                var length = random.Next(10000, 100000);
                Console.WriteLine(Watch.ElapsedMilliseconds + "普通方法完成结果:" + length);
            }
        }

      

           如图,先开始执行异步方法,结果却是用时较少的普通方法先完成。

  • 相关阅读:
    [Iterview English] Dimission and Employ
    委托(delegate)
    tensorflow(二十八):Keras自定义层,继承layer,model
    (三)任务型对话系统简介
    tensorflow(二十九):模型的保存
    tensorflow(二十七):Keras一句话训练fit
    python(五):argparse 模块
    tensorflow(二十六):Keras计算准确率和损失
    NLP(十):pytorch实现中文文本分类
    tensorflow(三十):keras自定义网络实战
  • 原文地址:https://www.cnblogs.com/hepeng/p/6163298.html
Copyright © 2011-2022 走看看