【C#】async与await介绍

发布于:2025-03-09 ⋅ 阅读:(78) ⋅ 点赞:(0)

1. 实例1

1.1 代码

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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Method1();
            Method2();
            Console.ReadKey();
        }

        public static async Task Method1()
        {
            Console.WriteLine("Method 1 Start................");

            await Task.Run(() =>
            {
                for (int i = 0; i < 100; i++)
                {
                    Console.WriteLine(" Method 1");
                }
            });

            //await的Task运行完以后,下面的代码才运行
            Console.WriteLine("Method 1 End................");
        }

        public static void Method2()
        {
            for (int i = 0; i < 25; i++)
            {
                Console.WriteLine(" Method 2");
            }
        }
    }
}

1.2 运行结果

  • Method2不会等待Method1运行结束再运行。
  • async方法中,await后面的代码也要等待await运行结束以后再运行。
    在这里插入图片描述
    在这里插入图片描述

2. 实例2

2.1 代码

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

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

        public static async void callMethod()
        {
            //方式1,Method3需要等待Method1的结果,所以Method1与Method2交替执行,Method3等Method1执行完毕再执行
            //await之后的需要等待前面的运行完再运行。
            Task<int> task = Method1();
            Method2();
            int count = await task;
            Method3(count);

            //方式2,顺序执行,运行完Method1再运行Method2再运行Method3
            //int count = await Method1();
            //Method2();
            //Method3(count);

            //方式3,报错。必须加await
            //int count = Method1();
            //Method2();
            //Method3(count);

            //方式4,Method1与[Method2,Method3]交替运行,Method2和Method3顺序执行
            //Method1();
            //Method2();
            //Method3(4);
        }

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

        public static void Method2()
        {
            for (int i = 0; i < 25; i++)
            {
                Console.WriteLine(" Method 2");
            }
        }

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

2.2 运行结果

  • 方式1的运行结果
    在这里插入图片描述

3. 总结

  • 调用async方法且不使用await修饰,不阻塞,直接运行。
  • 调用async方法且使用await修饰,阻塞等待,直到运行完成再运行后面的代码。

参考:


网站公告

今日签到

点亮在社区的每一天
去签到