async await 简单例子

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TaskTest
{
    class Program
    {
        static void Main(string[] args)
        {
            callMethod();
            Console.ReadKey();
        }

        public static async void callMethod()
        {
            Task task = Method1();
            Method2();
            int count = await task;
            Method3(count);
        }

        public static async Task Method1()
        {
            int count = 0;
            await Task.Run(() =>
            {
                for (int i = 0; i < 100; i++)
                {
                    Thread.Sleep(10);
                    Console.WriteLine(" Method 1");
                    count += 1;
                }
            });
            return count;
        }

        public static async void Method2()
        {
            await Task.Run(()=> {
                for (int i = 0; i < 25; i++)
                {
                    Thread.Sleep(10);
                    Console.WriteLine(" Method 2");
                }
            }); 
        }

        public static void Method3(int count)
        {
            Console.WriteLine("Total count is " + count);
        }
    }
}

async await 简单例子_第1张图片

你可能感兴趣的:(C#)