C# 异步Async与Await示例

 

一、初始了解

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

namespace SocketServer
{
    class Program
    {
        static void Main(string[] args)
        {
            callMethod();//方法中 Method1()是在异步中执行,与Method2()之间不相互依赖,Method3()依赖于Method1()
            Console.WriteLine("MainEnd");
            Console.ReadKey();
        }

        public static async void callMethod()
        {
            Task<int> task = Method1();//函数中的sleep模拟异步函数中耗时操作
            Method2();
            Console.WriteLine("M2End");
            Method2_1();//函数中的sleep模拟main函数中的耗时操作
            Console.WriteLine("M2_1End");
            int count = await task;
            Method3(count);
        }

        public static async Task<int> Method1()
        {
            int count = 0;
            await Task.Run(() =>
            {
                for (int i = 0; i < 20; i++)
                {
                    Console.WriteLine($" Method 1-{i}");
                    Thread.Sleep(100);
                    count += 1;
                }
            });
            return count;
        }

        public static void Method2()
        {
            Console.WriteLine($" Method 2");
        }

        public static void Method2_1()
        {
            for (int i = 0; i < 25; i++)
            {
                Console.WriteLine($" Method 2-{i}");
                Thread.Sleep(60);
            }
        }

        public static void Method3(int count)
        {
            Console.WriteLine("Total count is " + count);
        }
    }
}
View Code

运行结果:

 可以看出:方法1在Task中运行,方法2、方法2-1在主代码里运行,且互不干扰(实现了异步执行) 方法3在 await task; 之后,在Task执行完毕之后再执行方法3

二、常识记录

Task task=Task.Run(new Action(()=>{//执行耗时代码}));    task.Wait()会阻塞线程

Task.Any(task1,task2);任意一个完成即运行后续代码

三、尝试使用

1、后台加载数据,加载完成之后显示主页面

frm.Show();

var taskVis=Task.Run(new Action(()=>{//执行耗时代码})); 

var taskSql=Task.Run(new Action(()=>{//执行耗时代码})); 

Task.WaitAll(taskVis, taskSql);

frm.Close();

Main.Show();

原文地址:https://www.cnblogs.com/-hwh/p/13266382.html