一个例子 理解 await

本文通过一个C#异步编程示例介绍了如何使用async和await关键字来提高程序的响应性和效率。示例中创建了一个名为test的异步方法,该方法内部调用了另一个异步任务doo()。doo()方法利用Task.Run执行了长时间运行的操作,并在主线程中记录了操作前后的时间点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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




//1: test: await before
//doo0
//1: Main:inoke test after
//doo1
//doo2
//doo3
//doo4
//3: test: await after


namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            test();
            log("Main:inoke test after");
            Thread.Sleep(Timeout.Infinite);
        }


 
        static async void test()
        {
            log("test: await before");
            await doo();
            log("test: await after");
        }




        static async Task doo()
        {
             await Task.Run(() => {
                 for (int i = 0; i < 5; i++)
                 {
                    Console.WriteLine("doo" + i.ToString());
                     Thread.Sleep(1000);
                 }


             });
           
        }


        static void log(string msg)
        {
            Console.WriteLine("{0}: {1}", Thread.CurrentThread.ManagedThreadId, msg);
        }


    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值