C# 异步链接阻止webapi调用

C# 异步链接阻止webapi调用,c#,asp.net-web-api,async-await,C#,Asp.net Web Api,Async Await,我有一个流程:WebApi>ServiceFramework>DBLayer>MongoDB 因为它是一个新的应用程序,所以我确保在所有层中从头开始都是异步的。然而,当我的DB层有异步代码时,webapi永远不会得到响应 API控制器 [HttpGet] public IHttpActionResult GetAllRecords() { var result = FrameworkApi.GetRecords().Result; return Ok(result); } 以上调用

我有一个流程:WebApi>ServiceFramework>DBLayer>MongoDB

因为它是一个新的应用程序,所以我确保在所有层中从头开始都是异步的。然而,当我的DB层有异步代码时,webapi永远不会得到响应

API控制器

[HttpGet]
public IHttpActionResult GetAllRecords()
{
   var result = FrameworkApi.GetRecords().Result;
   return Ok(result);
}
以上调用>框架API

public async Task<List<Record>> GetRecords()
{
    return await FrameworkDbApi.GetRecords();
}
公共异步任务GetRecords() { return wait frameworkbapi.GetRecords(); } 以上调用>DB框架API(调用MongoDB)

公共异步任务GetRecords() { 返回等待任务。运行(()=> NoSqlDocumentClient.GetDefaultDatabase().Result。 GetCollection(“record”).AsQueryable().ToList(); //下面的同步版本可以工作,但无法达到目的 //返回NoSqlDocumentClient.GetDefaultDatabase().Result //.GetCollection(“记录”).AsQueryable().ToList(); } 然而,当通过测试用例调用DBLayer或Framework中的操作时,我确实得到了结果。但当通过WebApi控制器调用时,异步版本永远不会返回响应,而同步版本工作正常

但当通过WebApi控制器调用时,异步版本永远不会 在同步版本正常工作时返回响应

这是因为您的实际请求处于死锁状态。当您通过WebAPI调用该方法时,您会看到死锁,而测试没有死锁,测试运行正常。这就是你为什么这么做的原因

为了避免死锁,您的调用链应该如下所示(这就是“始终异步”的含义):

[HttpGet]
公共异步任务GetAllRecordsAsync()
{
var result=await FrameworkApi.GetRecordsAsync();
返回Ok(结果);
}
公共任务GetRecordsAsync()
{
返回FrameworkBapi.GetRecordsAsync();
}
公共异步任务GetRecordsAsync()
{
var result=await NoSqlDocumentClient.GetDefaultDatabase();
返回result.GetCollection(“记录”).AsQueryable().ToList();
}
但当通过WebApi控制器调用时,异步版本永远不会 在同步版本正常工作时返回响应

这是因为您的实际请求是死锁的。当您通过WebAPI调用该方法时(该方法具有死锁),您会看到死锁,而您的测试没有死锁,测试运行正常。这就是您的原因

为了避免死锁,您的调用链应该如下所示(这就是“始终异步”的含义):

[HttpGet]
公共异步任务GetAllRecordsAsync()
{
var result=await FrameworkApi.GetRecordsAsync();
返回Ok(结果);
}
公共任务GetRecordsAsync()
{
返回FrameworkBapi.GetRecordsAsync();
}
公共异步任务GetRecordsAsync()
{
var result=await NoSqlDocumentClient.GetDefaultDatabase();
返回result.GetCollection(“记录”).AsQueryable().ToList();
}
public async Task<List<Record>> GetRecords()
{
    return await Task.Run(() =>                
       NoSqlDocumentClient.GetDefaultDatabase().Result.
       GetCollection<Record>("record").AsQueryable().ToList());            

      //following Synchronous version works..but defeats the purpose  
      //return NoSqlDocumentClient.GetDefaultDatabase().Result
      //       .GetCollection<Record>("record").AsQueryable().ToList();
}
[HttpGet]
public async Task<IHttpActionResult> GetAllRecordsAsync()
{
   var result = await FrameworkApi.GetRecordsAsync();
   return Ok(result);
}

public Task<List<Record>> GetRecordsAsync()
{
    return FrameworkDbApi.GetRecordsAsync();
}

public async Task<List<Record>> GetRecordsAsync()
{
    var result = await NoSqlDocumentClient.GetDefaultDatabase();
    return result.GetCollection<Record>("record").AsQueryable().ToList();          
}