zoukankan      html  css  js  c++  java
  • C# async await的使用

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

    async标记的函数返回值必须为 void ,Task,Task<TResult>

    await 必须修饰Task 或者Task<TResult>

    await之后的代码运行线程:对于纯console工程,还是耗时任务的线程,

    对于winform线程,则是调用线程。

    典型代码

            public static async Task<int> CalAsync()
            {
                string tid = Thread.CurrentThread.ManagedThreadId.ToString();
                Console.WriteLine("当前位置async函数,await之前,线程ID"+tid);
                int result = await Task.Run(new Func<int>(Cal));
                tid = Thread.CurrentThread.ManagedThreadId.ToString();
                Console.WriteLine("当前位置async函数,await之后,线程ID" + tid);
                return result;
            }

    全部代码

    class Program
        {
            static void Main(string[] args)
            {
                string tid = Thread.CurrentThread.ManagedThreadId.ToString();
                Console.WriteLine("当前位置主函数,调用async异步之前,线程ID"+tid);
                Task<int> t = CalAsync();
                Console.WriteLine("当前位置主函数,调用async异步之后,线程ID" + tid);
                Console.Read();
    
            }
            public static async Task<int> CalAsync()
            {
                string tid = Thread.CurrentThread.ManagedThreadId.ToString();
                Console.WriteLine("当前位置async函数,await之前,线程ID"+tid);
                int result = await Task.Run(new Func<int>(Cal));
                tid = Thread.CurrentThread.ManagedThreadId.ToString();
                Console.WriteLine("当前位置async函数,await之后,线程ID" + tid);
                return result;
            }
    
            public static int Cal()
            {
                string tid = Thread.CurrentThread.ManagedThreadId.ToString();
                Console.WriteLine("当前位置耗时函数,线程ID"+tid);
                int sum = 0;
                for (int i = 0; i < 999; i++)
                {
                    sum = sum + i;
                }
                Console.WriteLine("当前位置耗时函数完成,线程ID" + tid);
                return sum;
            }
    
    
        }
    View Code

    输入内容

    winform中优雅的实现

    private async void button1_Click(object sender, EventArgs e)
            {
                var t = Task.Run(() =>
                {
                    Thread.Sleep(5000);
                    return "Returning from TimeConsuming task";
                });
                this.Text = await t;
            }

    参考

    https://www.cnblogs.com/doforfuture/p/6293926.html

  • 相关阅读:
    大型web系统分布式架构
    与MSN聊天的PowerTalk两个示例
    PowerTalk的四个示例代码
    PowerTalk在十月份左右会有新的版本
    PowerTalk控件 制作 即时通信 聊天室 产品咨询系统 支持与MSN的控件
    PowerTalk有些对不住大家
    自动生成实体sql工具的IDEvs2005工具(源代码+程序)
    C#字符串类快速编译器
    小菜编程成长记系列
    一道简单的编程题,不过您做对了吗?
  • 原文地址:https://www.cnblogs.com/noigel/p/10669753.html
Copyright © 2011-2022 走看看