C# 理解async和await的用法

1:在C#中, async标记了一个包含异步执行的函数,通过async标记的函数若在主线程中直接调用,则函数一开始仍在主线程中执行;

2:aysnc标记的函数内部必须包含await标记需要异步执行的函数,若当前函数在主线程中直接调用,则await标记前的代码在主线程中执行,await标记后的代码在其异步子线程中执行;

3:async标记的函数返回值必须为void、Task、Task< TResult> 类型,可以理解为async标记的函数返回的是 “空”、“即将执行的任务”、“带结果的即将执行的任务”实例;

4:async标记的函数可以继续往下调用async标记函数

总结
C#中async与await异步编程,可以理解为:

  1. async声明了一个包含异步执行代码的函数,该函数执行时不会阻塞调用线程;

  2. await存在于async函数中,声明了一个异步执行入口,程序动态运行时从该入口创建并进入一个异步线程环境,并在该线程执行任务实例及任务实例返回之后的代码;

  3. 一个async函数中声明多个await关键字时,程序将代码顺序创建并进入异步子线程执行任务实例及任务实例返回之后的代码直到下一个await声明处, 最后一个await声明之后的代码会在最后一个异步子线程中执行 ;

  4. await标记的右侧代码返回或定义了一个任务实例,该实例由需要异步执行的目标耗时函数初始化,并在最终定义处触发异步执行。

winfrom实现
界面一个button,一个textbox,一个timer。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MyTest.多线程
{
    public partial class Test : Form
    {
        static StringBuilder sb = new StringBuilder();
        static int step = -1;
        public Test()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            step = -1;
            sb = new StringBuilder();
            string thread_id = Thread.CurrentThread.ManagedThreadId.ToString();
            sb.AppendLine(string.Format("①当前线程ID:{0}", thread_id));
            Task<int> t = Async3();//调用异步线程执行
            sb.AppendLine("④/⑤主线程结束.");//直接运行下去   
            timer1.Enabled = true;       
        }
        public static int Async1()
        {
            string thread_id = Thread.CurrentThread.ManagedThreadId.ToString();
            sb.AppendLine(string.Format("⑤/④当前线程ID:{0}", thread_id));
            int sum = 0;
            for (int i = 0; i < 999; i++)
            {
                sum += i;
            }
            return sum;
        }

        public static async Task<int> Async2()
        {
            string thread_id = Thread.CurrentThread.ManagedThreadId.ToString();
            sb.AppendLine(string.Format("③当前线程ID:{0}", thread_id));
            int result = await Task.Run(new Func<int>(Async1));//await标记之后,代码在子线程中执行。
            thread_id = Thread.CurrentThread.ManagedThreadId.ToString();
            sb.AppendLine(string.Format("⑥当前线程ID:{0},result:{1}", thread_id, result));
            return result;
        }

        public static async Task<int> Async3()
        {
            string thread_id = Thread.CurrentThread.ManagedThreadId.ToString();
            sb.AppendLine(string.Format("②当前线程ID:{0}", thread_id));
            int result = await Async2();
            thread_id = Thread.CurrentThread.ManagedThreadId.ToString();
            sb.AppendLine(string.Format("⑦当前线程ID:{0},result:{1}", thread_id, result));
            step = 1;
            return result;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (step > 0)
                timer1.Enabled = false;
            textBox1.Text = sb.ToString();
        }
    }
}

运行实例:
在这里插入图片描述

在这里插入图片描述
参考原文:https://blog.csdn.net/a462533587/article/details/82261468?ops_request_misc=&request_id=&biz_id=102&utm_term=.net%20%20sync%E5%92%8Cawait&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-7-.pc_search_download_positive&spm=1018.2226.3001.4187

  • 4
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yangzm996

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值