c# 异步运行单线程?

标签 c# async-await c#-5.0

我正在阅读 http://msdn.microsoft.com/en-US/library/vstudio/hh191443.aspx . 示例代码:

async Task<int> AccessTheWebAsync()
{ 
    // You need to add a reference to System.Net.Http to declare client.
    HttpClient client = new HttpClient();

    // GetStringAsync returns a Task<string>. That means that when you await the 
    // task you'll get a string (urlContents).
    Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");

    // You can do work here that doesn't rely on the string from GetStringAsync.
    DoIndependentWork();

    // The await operator suspends AccessTheWebAsync. 
    //  - AccessTheWebAsync can't continue until getStringTask is complete. 
    //  - Meanwhile, control returns to the caller of AccessTheWebAsync. 
    //  - Control resumes here when getStringTask is complete.  
    //  - The await operator then retrieves the string result from getStringTask. 
    string urlContents = await getStringTask;

    // The return statement specifies an integer result. 
    // Any methods that are awaiting AccessTheWebAsync retrieve the length value. 
    return urlContents.Length;
}

该页面还说:

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread

这种“不创建额外线程”是否适用于标记为异步的方法范围内?

我想,为了让 GetStringAsync 和 AccessTheWebAsync 同时运行(否则 GetStringAsync 将永远不会完成,因为 AccessTheWebAsync 现在拥有控制权),最终 GetStringAsync 必须在与 AccessTheWebAsync 的线程不同的线程上运行。

对我来说,编写异步方法仅在等待的方法也是异步的(它已经使用额外的线程来并行执行自己的事情)时不添加更多线程时才有用

我的理解正确吗?

最佳答案

这是 async 强大功能的关键。 GetStringAsync 和其他自然异步操作不需要线程GetStringAsync 只是发出 HTTP 请求并注册一个回调以在服务器回复时运行。不需要一个线程来等待服务器响应。

实际上,线程池只用了一点点。在上面的示例中,由 GetStringAsync 注册的回调将在线程池线程上执行,但它所做的只是通知 AccessTheWebAsync 它可以继续执行。

我有一个 async intro blog post您可能会发现有帮助。

关于c# 异步运行单线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17734420/

相关文章:

c# - 将欧拉转换为矩阵并将矩阵转换为欧拉

c# - 如何在C#中成功下载一个.exe文件?

nant - 使用 Nant 构建 .NET 4.5 项目

c# 5 异步作为糖语法(或不是)?

c# - 如何在 linq 中的逗号分隔字段之间进行搜索

c# - 在 c# 中解压由 php 的 gzcompress() 压缩的字符串

c# - 覆盖 Json.Net 中的默认基元类型处理

firebase - 如何从 flutter 中的异步任务检索到的数据中将图像加载到卡中?

c# - Task.WaitAll 在 ASP.NET 中挂起多个等待任务

c# - 对多个任务使用 async/await