想了解异步 [英] Want to understand async
问题描述
我用异步编码一点点,但我真的不完全了解如何使用它 - 虽然我理解这个概念,为什么我需要它
下面是我的设置:
我有一个Web API,我会从我的ASP.NET MVC应用程序,我的Web API将调用DocumentDB调用。在code样品,我看到很多等待的关键字,同时发送查询DocumentDB。
我糊涂了,如果我需要让我的索引操作方法在我的MVC应用程序异步?
我也糊涂了,如果我在CreateEmployee()方法,在我的Web API应该是异步?
什么是在这种情况下使用异步的正确方法?
下面是我的code(这code目前给我的错误,因为我的MVC的操作方法是不是异步)
---- ASP.NET MVC应用程序code ----
公众的ActionResult指数()
{ 员工EMP =新员工();
emp.FirstName =约翰;
emp.LastName =李四;
emp.Gender =M;
emp.Ssn =123-45-6789; 使用(VAR的客户=新的HttpClient())
{
client.BaseAddress =新的URI(http://myWebApi.com);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(新MediaTypeWithQualityHeaderValue(应用/ JSON)); HTT presponseMessage响应=等待client.PostAsJsonAsync(HR /创建/ newemployee,EMP);
如果(response.IsSuccessStatus code)
{
EMP =等待response.Content.ReadAsAsync<员工>();
}
} //显示员工信息
返回查看(EMP);
}
----网页API code ----
私有静态只读字符串endPointUrl = ConfigurationManager.AppSettings [EndPointUrl];
私人静态只读字符串authorizationKey = ConfigurationManager.AppSettings [AuthorizationKey];
私人静态只读字符串databaseId = ConfigurationManager.AppSettings [DatabaseId];
私有静态DocumentClient客户端;公共静态异步任务<员工>在CreateEmployee(员工EMP)
{
尝试
{
//创建一个文档客户端
使用(客户端=新DocumentClient(新的URI(endPointUrl),authorizationKey))
{
//获取数据库
VAR数据库=等待GetDatabaseAsync(); //获取文档集合
VAR收集=等待GetCollectionAsync(database.SelfLink,员工); 等待client.CreateDocumentAsync(collection.SelfLink,EMP); //进一步处理员工
}
}
抓住
{
//处理错误
} 返回雇员;
}私有静态异步任务< DocumentCollection> GetCollectionAsync(字符串DBLINK,字符串ID)
{
DocumentCollection集合= client.CreateDocumentCollectionQuery(DBLINK)。凡(C => c.Id == ID)。.ToArray()FirstOrDefault(); 返回集合;
}私有静态异步任务<数据库> GetDatabaseAsync()
{
database数据库= client.CreateDatabaseQuery()式(DB => db.Id == databaseId)。.ToArray()FirstOrDefault()。 返回数据库;
}
您只能使用等待
一个方法中,如果该方法是异步
和异步
方法需要返回任务
,任务< T>
或无效
虽然无效
返回异步
方法是保留给事件处理程序,因为它们内部抛出的异常被咽下去,你不能等待
其完成或链中的后续任务。
我觉得你的首页
动作需要异步
并返回任务<的ActionResult&GT ;
和您的在CreateEmployee
方法需要,因为它是用是异步
以及等待
里面。
请参阅异步编程 最佳实务的一些准则和时如何使用异步的await
I've used async coding a little bit but I don't really fully understand how to use it -- though I understand the concept and why I need it.
Here's my set up:
I have a Web API that I will call from my ASP.NET MVC app and my Web API will call DocumentDB. In code samples, I see a lot of await keywords while sending queries to DocumentDB.
I'm confused if I need to make my Index action method in my MVC app async? I'm also confused if my CreateEmployee() method in my Web API should be async?
What is the right way to use async in this scenario?
Here's my code (This code is currently giving me errors because my MVC action method is not async) ---- ASP.NET MVC App Code ----
public ActionResult Index()
{
Employee emp = new Employee();
emp.FirstName = "John";
emp.LastName = "Doe";
emp.Gender = "M";
emp.Ssn = "123-45-6789";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://myWebApi.com");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsJsonAsync("hr/create/newemployee", emp);
if (response.IsSuccessStatusCode)
{
emp = await response.Content.ReadAsAsync<Employee>();
}
}
// Display employee info
return View(emp);
}
---- Web API Code ----
private static readonly string endPointUrl = ConfigurationManager.AppSettings["EndPointUrl"];
private static readonly string authorizationKey = ConfigurationManager.AppSettings["AuthorizationKey"];
private static readonly string databaseId = ConfigurationManager.AppSettings["DatabaseId"];
private static DocumentClient client;
public static async Task<Employee> CreateEmployee(Employee emp)
{
try
{
//Create a Document client
using (client = new DocumentClient(new Uri(endPointUrl), authorizationKey))
{
//Get the database
var database = await GetDatabaseAsync();
//Get the Document Collection
var collection = await GetCollectionAsync(database.SelfLink, "Employees");
await client.CreateDocumentAsync(collection.SelfLink, emp);
// Further process employee
}
}
catch
{
// Handle error
}
return employee;
}
private static async Task<DocumentCollection> GetCollectionAsync(string dbLink, string id)
{
DocumentCollection collection = client.CreateDocumentCollectionQuery(dbLink).Where(c => c.Id == id).ToArray().FirstOrDefault();
return collection;
}
private static async Task<Database> GetDatabaseAsync()
{
Database database = client.CreateDatabaseQuery().Where(db => db.Id == databaseId).ToArray().FirstOrDefault();
return database;
}
you can only use await
inside a method if that method is async
and async
methods need to return Task
, Task<T>
or void
although void
returning async
methods are reserved for event handlers because the exceptions thrown within them are swallowed and you cannot await
their completion or chain subsequent tasks.
I think your Index
action needs to be async
and return a Task<ActionResult>
and your CreateEmployee
method needs to be async
as well as it is using await
inside it.
See Best Practices in Asynchronous Programming for some guidelines on when and how to use async-await
这篇关于想了解异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!