C# ASP.NET MVC控制器在读取文件时出错

C# ASP.NET MVC控制器在读取文件时出错,c#,asp.net-mvc,async-await,C#,Asp.net Mvc,Async Await,我有一个非常简单的控制器,它尝试使用wait/async方法读取本地文件的内容。使用XUnit或从控制台应用程序进行测试非常有吸引力。 但是,当从以下控制器使用时,应用程序会在wait reader.ReadToEndAsync()上阻塞,再也不会返回 你知道会出什么问题吗!(可能与某些同步上下文有关吗?) 控制器: public ActionResult Index() { profiles.Add(_local.GetProfileAsync(id).Result); r

我有一个非常简单的控制器,它尝试使用wait/async方法读取本地文件的内容。使用XUnit或从控制台应用程序进行测试非常有吸引力。 但是,当从以下控制器使用时,应用程序会在wait reader.ReadToEndAsync()上阻塞,再也不会返回

你知道会出什么问题吗!(可能与某些同步上下文有关吗?)

控制器:

 public ActionResult Index()
 {
    profiles.Add(_local.GetProfileAsync(id).Result);
    return View(profiles);
 }
GetProfileAsync方法如下所示:

public override async Task<Profile> GetProfileAsync(long id)
{
    // Read profile
    var filepath = Path.Combine(_directory, id.ToString() , "profile.html");
    if (!File.Exists(filepath))
        throw new FileNotFoundException(string.Format("File not found: {0}", filepath));
    string content;
    using (var fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
    {
        using (var reader = new StreamReader(fs))
        {
            content = await reader.ReadToEndAsync();
        }
    }
 ...
    return profile;
 }
公共重写异步任务GetProfileAsync(长id)
{
//读取配置文件
var filepath=Path.Combine(_目录,id.ToString(),“profile.html”);
如果(!File.Exists(filepath))
抛出新的FileNotFoundException(string.Format(“未找到文件:{0}”,filepath));
字符串内容;
使用(var fs=new FileStream(filepath,FileMode.Open,FileAccess.Read))
{
使用(变量读取器=新的StreamReader(fs))
{
content=wait reader.ReadToEndAsync();
}
}
...
回报曲线;
}

是的,这是一个同步上下文问题。通过调用
Result
而不是使用
wait
,导致死锁;我解释一下

总之,
await
在恢复
async
方法时,默认情况下将尝试重新输入上下文。但是ASP.NET上下文一次只允许一个线程进入,并且该线程在调用
Result
时被阻塞(等待
async
方法完成)

要解决此问题,请使用
wait
而不是
Result

public async Task<ActionResult> Index()
{
  profiles.Add(await _local.GetProfileAsync(id));
  return View(profiles);
}
公共异步任务索引()
{
Add(wait_local.GetProfileAsync(id));
返回视图(配置文件);
}

是的,这是一个同步上下文问题。通过调用
Result
而不是使用
wait
,导致死锁;我解释一下

总之,
await
在恢复
async
方法时,默认情况下将尝试重新输入上下文。但是ASP.NET上下文一次只允许一个线程进入,并且该线程在调用
Result
时被阻塞(等待
async
方法完成)

要解决此问题,请使用
wait
而不是
Result

public async Task<ActionResult> Index()
{
  profiles.Add(await _local.GetProfileAsync(id));
  return View(profiles);
}
公共异步任务索引()
{
Add(wait_local.GetProfileAsync(id));
返回视图(配置文件);
}