相关疑难解决方法(0)

想要了解异步

我已经使用了异步编码,但我并不完全理解如何使用它 - 尽管我理解这个概念以及为什么需要它.

这是我的设置:

我有一个Web API,我将从我的ASP.NET MVC应用程序调用,我的Web API将调用DocumentDB.在代码示例中,我在向DocumentDB发送查询时看到了很多等待关键字.

如果我需要在我的MVC应用程序异步中使我的索引操作方法,我很困惑?如果我的Web API中的CreateEmployee()方法应该是异步的,我也很困惑?

在这种情况下使用异步的正确方法是什么?

这是我的代码(这段代码目前给我错误,因为我的MVC动作方法不是异步)---- 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);
}
Run Code Online (Sandbox Code Playgroud)

---- Web API代码----

private static readonly …
Run Code Online (Sandbox Code Playgroud)

c# async-await asp.net-web-api2 azure-cosmosdb

9
推荐指数
2
解决办法
2万
查看次数

DocumentDB调用挂起

我正在调用我的DocumentDB数据库来查询一个人.如果该人不在数据库中,那么我正在尝试将该人插入我的收藏中.

当我检查集合时,我看到正在创建新人,但我的代码似乎挂起了我进行第二次调用以将人插入集合的地方.知道我的代码挂起的原因吗?我没有包括节省空间的所有代码,例如GetDatabaseAsync(),GetCollectionAsync()等都在工作.

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, "People");

   string sqlQuery = "SELECT * FROM People f WHERE f.id = \"" + user.PersonId + "\"";

   dynamic doc = client.CreateDocumentQuery(collection.SelfLink, sqlQuery).AsEnumerable().FirstOrDefault();

   if (doc == null)
   {
      // User is not in the database. Add user to the database
      try
      {
         **// This is where the code is hanging. It creates the user …
Run Code Online (Sandbox Code Playgroud)

azure-cosmosdb

4
推荐指数
1
解决办法
2488
查看次数