C#异步 await

用到了就随时记录下web

当咱们处理UI和on按钮单击时,咱们使用一个长时间运行的方法,好比读取一个大文件或其余须要很长时间的东西,在这种状况下,整个应用程序必须等待才能完成整个任务。编程

换句话说,若是同步应用程序中的任何进程被阻塞,整个应用程序将被阻塞,咱们的应用程序将中止响应,直到整个任务完成。异步

异步编程在这种状况下很是有用。经过使用异步编程,应用程序能够继续进行不依赖于完成整个任务的其余工做。async

若是任何第三个方法 Method3与method1有依赖关系,那么它将在await关键字的帮助下等待method1的完成。svg

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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            call();
            Console.ReadKey();
        }


        public static async void call()
        {
            Task<int> task1 = Method1();
            Method2();
            //
            int count = await task1;
            Method3(count);

        }
        public static async Task<int> Method1()
        {
            int count = 0;
            await Task.Run(() =>
            {
                for (int i = 0; i < 1225; i++)
                {
                    Console.WriteLine("methid1");
                    count += 1;
                }
            });
            return count;
        }


        public static  void Method2()
        {
            for (int i = 0; i < 1225; i++)
            {
                Console.WriteLine(" Method 2");
            }
        }

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

await 必须与async 同时使用异步编程

class Program  
{  
    static void Main()  
    {  
        Task task = new Task(CallMethod);  
        task.Start();  
        task.Wait();  
        Console.ReadLine();  
    }  
  
    static async void CallMethod()  
    {  
        string filePath = "E:\\sampleFile.txt";  
        Task<int> task = ReadFile(filePath);  
  
        Console.WriteLine(" Other Work 1");  
        Console.WriteLine(" Other Work 2");  
        Console.WriteLine(" Other Work 3");  
  
        int length = await task;  
        Console.WriteLine(" Total length: " + length);  
  
        Console.WriteLine(" After work 1");  
        Console.WriteLine(" After work 2");  
    }  
  
    static async Task<int> ReadFile(string file)  
    {  
        int length = 0;  
  
        Console.WriteLine(" File reading is stating");  
        using (StreamReader reader = new StreamReader(file))  
        {  
            // Reads all characters from the current position to the end of the stream asynchronously 
            // and returns them as one string. 
            string s = await reader.ReadToEndAsync();  
  
            length = s.Length;  
        }  
        Console.WriteLine(" File reading is completed");  
        return length;  
    }  
}

在这里插入图片描述