【发布时间】:2015-07-23 13:28:02
【问题描述】:
我正在开发一个 MVC Web 应用程序,它允许我通过 Web 服务异步管理我的数据。
据我了解,这允许访问运行本网站的服务器的应用程序池的 CPU 线程在发出请求后返回应用程序池,以便它们可用于服务其他请求而不会停止整个线程。
假设我的理解是正确的(尽管它可能措辞不当),我不得不考虑什么时候应该await 事情。考虑下面的函数:
public async Task<ActionResult> Index()
{
List<User> users = new List<User>();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:41979");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("api/user/");
if (response.IsSuccessStatusCode)
{
users = await response.Content.ReadAsAsync<List<User>>();
}
}
return View(users);
}
我的所有函数看起来都相似,只是它们对 Web 服务返回的数据执行不同的操作,我想知道,我是否也应该等待返回?
类似:
return await View(users);
或
await return View(users);
我的意思是该网站到目前为止运行良好,只是我对 Web 服务应该发送回客户端网站的确切内容有些困惑,但由于我是涉及 Web 服务的开发新手,我仍然想知道我做事是否正确,这已经困扰我一段时间了。
【问题讨论】:
标签: c# multithreading web-services asynchronous async-await