Skip to content
标签
欢迎扫码关注公众号

C# async / await 的用法

使用 async / await 关键字可以方便的实现异步的效果。

示例代码:

cs
using System;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncSample
{
    class Program
    {
        static void Main(string args)
        {
            Console.WriteLine("Main Start.(ThreadId:{0})", Thread.CurrentThread.ManagedThreadId);
            PrintAsyncThreadInfo(); // 这里不会阻塞线程
            Console.WriteLine("Main End.(ThreadId:{0})", Thread.CurrentThread.ManagedThreadId);
            Console.ReadLine();
        }

        static async void PrintAsyncThreadInfo()
        {
            Console.WriteLine("PrintAsyncThreadInfo Start.(ThreadId:{0})", Thread.CurrentThread.ManagedThreadId);
            await PrintAwaitThreadInfo(); // 新起一个线程执行 Task
            // 之后的方法被封装成代理,Task 结束后再调用
            Console.WriteLine("PrintAsyncThreadInfo End.(ThreadId:{0})", Thread.CurrentThread.ManagedThreadId);
        }

        static Task PrintAwaitThreadInfo()
        {
            return Task.Run(() => {
                Console.WriteLine("PrintAwaitThreadInfo Start.(ThreadId:{0})", Thread.CurrentThread.ManagedThreadId);

                Console.WriteLine("PrintAwaitThreadInfo End.(ThreadId:{0})", Thread.CurrentThread.ManagedThreadId);
            });
        }

    }
}

输出结果:

Main Start.(ThreadId:1)
PrintAsyncThreadInfo Start.(ThreadId:1)
PrintAwaitThreadInfo Start.(ThreadId:3)
PrintAwaitThreadInfo End.(ThreadId:3)
Main End.(ThreadId:1)
PrintAsyncThreadInfo End.(ThreadId:3)

由上面的输出可以发现:

  • Main 方法的 Start 和 End 的线程 ID 为 1;
  • PrintAwaitThreadInfo 的 Start 和 End 的线程 ID 为 3;
  • PrintAsyncThreadInfo 的 Start 线程 ID 为 1,End 线程 ID 为 3;

可以说明 await 关键字调用的方法及之后的处理是在新线程中执行的

Main 的 End 在 PrintAsyncThreadInfo 的 End 之前执行说明 await 关键字不阻塞线程

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.