关于Async和Await的工作方式C# [英] Regarding how Async and Await works c#

查看:68
本文介绍了关于Async和Await的工作方式C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在该站点上看到一些有关异步和等待使用的帖子.很少有人说Async和Await在单独的后台线程上完成其工作意味着生成了一个新的后台线程,很少有人说这意味着Async和Await没有启动任何单独的后台线程来完成其工作.

i saw some post regarding Async and Await usage in this site. few people are saying that Async and Await complete its job on separate background thread means spawn a new background thread and few people are saying no means Async and Await does not start any separate background thread to complete its job.

所以任何人只要告诉我使用Async和Await时会发生什么.

so anyone just tell me what happen in case of Async and Await when it is used.

class Program
{
    static void Main(string[] args)
    {
        TestAsyncAwaitMethods();
        Console.WriteLine("Press any key to exit...");
        Console.ReadLine();
    }

    public async static void TestAsyncAwaitMethods()
    {
        await LongRunningMethod();
    }

    public static async Task<int> LongRunningMethod()
    {
        Console.WriteLine("Starting Long Running method...");
        await Task.Delay(5000);
        Console.WriteLine("End Long Running method...");
        return 1;
    }
}

输出为:

Starting Long Running method...
Press any key to exit...
End Long Running method...

推荐答案

问题是async/await异步有关,而不与线程有关.

The problem is that async/await is about asynchrony, not threads.

如果使用Task.Run,它将确实使用后台线程(通过线程池,通过任务并行库).

If you use Task.Run, it will indeed use a background thread (via the Thread Pool, via the Task Parallel Library).

但是,对于IO操作,它依靠IO完成端口来通知操作何时完成.

However, for IO operations it relies on IO Completion ports to notify when the operation is complete.

async/await唯一保证的是,当操作完成时,它将返回到开始时所在的SynchronizationContext中的调用方.实际上,这意味着它将在UI线程(在Windows应用程序中)或可以返回HTTP响应的线程(在ASP.NET中)返回

The only guarantee async/await makes is that when an operation completes, it will return to your caller in the SynchronizationContext that was there when it began. In practical terms, that means it will return on the UI Thread (in a Windows application) or to a thread that can return the HTTP Response (in ASP.NET)

这篇关于关于Async和Await的工作方式C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆