C# async await 异步编程

发布时间 2023-11-26 10:01:02作者: Simian_2018_12_22

开始

异步方法不等于多线程,await是等但又是不等。

1. 调用系统的async方法
static async Task Main(string[] args)
{
    await File.WriteAllTextAsync("a.txt", "xxxxxxxxxx");
    string s = await File.ReadAllTextAsync("a.txt");
    Console.WriteLine(s);
}

使用await关键字调用async方法,await表示等待await File.WriteAllTextAsync("a.txt", "xxxxxxxxxx");执行到这里时,如果这句话没执行完成,后面的代码不会运行。

  • 如果方法中使用了await关键字,则方法必须改为async修饰的方法。
  • Main 函数使用async修饰后,返回值要改成Task
  • 如果是winform里面的按钮或其他事件用async修饰后,返回值不需要修改为Task
  • 返回值代表的意思:Task=void;Task=int;Task=string
2. 不使用await调用系统的async方法
static void Main(string[] args)
{
    // 调用无返回值使用wait方法
    File.WriteAllTextAsync("a.txt", "xxxxxxxxxx").Wait();
    // 调用有返回值使用Result属性
    string s = File.ReadAllTextAsync("a.txt").Result;
    Console.WriteLine(s);
}
3. 使用Delay实现sleep等延时等待效果
  • 在多线程中,如果需要等待几秒后再执行,则需要使用Thread.Sleep(1000);来等待,但是这个函数会造成主线程堵塞,将系统卡住,等计时结束才会重新恢复系统。而使用await Task.Delay(1000)则不会造成系统堵塞。
static async Task Main(string[] args)
{

    Console.WriteLine("1");
    await mm("aa");
    Console.WriteLine("2");
}
static async Task mm(string n)
{
    Console.WriteLine(n + "开始");
    await Task.Delay(5000);
    Console.WriteLine(n + "结束");
}

上述代码的执行结果是:

1
aa开始
等待5000毫秒后。。。
aa结束
2
4.线程池中使用async
static void Main(string[] args)
{
    ThreadPool.QueueUserWorkItem(async (obj) =>
    {
        while (true)
        {
            Console.WriteLine("xxxxxxxxxxxx");
        }
    });
    Console.ReadLine();
}

因为只是在方法中使用了async所以不需要将方法用async修饰,方法的返回值也不需要修改为Task,只有方法中用到了await才需要使用async修饰方法。