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

  • 相关阅读:
    Enterprise Library 4.1 Data Access Block 快速使用图文笔记
    敏捷开发(名字起得很帅,很忽悠人)原则 括号里面加了自己的理解笔记
    与弟弟谈话的摘要
    练习:选头像控件
    [转]保护你的flash(as3)程序基于socket方式传送swf文件
    Silverlight 又多了一套skin
    Silverlight制作逐帧动画
    Silverlight Spy 2 源代码查看器
    跨平台开发silverlight
    Silverlight 2 搜索照片 Live
  • 原文地址:https://www.cnblogs.com/noigel/p/10669753.html
Copyright © 2011-2022 走看看