异步

 class Program
    {
        static void Main(string[] args)
        {
            callMethod();
            //Console.WriteLine("接口访问开始");
            //string s = testreturn();
            //Console.WriteLine(s);
            //Method1(s);
            //Console.WriteLine("接口访问结束");
            Console.ReadKey();
        }
        public static async Task<string> testreturn()
        {
            Console.WriteLine("1");
            Thread.Sleep(2000); //模拟耗时
            for (int i = 0; i < 200; i++)
            {

            };
            Console.WriteLine("2");
            return "OK";
        }
        public static async void callMethod()
        {
            string s ="NO";
            Console.WriteLine("接口访问开始");
            //string s = await testreturn();
            for (int i = 0; i < 20; i++)
            {
                Console.WriteLine(i);
                if (i == 9) { s = "OK"; }
            };
            Console.WriteLine("接口访问进行中");
            var n=Method1(s);
            Console.WriteLine("接口访问结束");
            //Task<int> task = Method1();
            //Method2();
            //int count = await task;
            //Method3(count);
        }

        public static async Task<int> Method1(string s)
        {
            int count = 0;
            await Task.Run(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine(s);
                    count += 1;
                }
            });
            return count;
        }
    }

 

posted @ 2021-01-29 15:04  越吃越瘦  阅读(32)  评论(0编辑  收藏  举报