我有一个非常简单的ASP.NET MVC 4控制器:
public class HomeController : Controller
{
private const string MY_URL = "http://smthing";
private readonly Task<string> task;
public HomeController() { task = DownloadAsync(); }
public ActionResult Index() { return View(); }
private async Task<string> DownloadAsync()
{
using (WebClient myWebClient = new WebClient())
return await myWebClient.DownloadStringTaskAsync(MY_URL)
.ConfigureAwait(false);
}
}
Run Code Online (Sandbox Code Playgroud)
当我启动项目时,我看到了我的视图,它看起来很好,但是当我更新页面时,我收到以下错误:
[InvalidOperationException:在异步操作仍处于挂起状态时完成异步模块或处理程序.
为什么会这样?我做了几个测试:
task = DownloadAsync();从构造函数中删除并将其放入Index方法中它将正常工作而没有错误.DownloadAsync()身体return await Task.Factory.StartNew(() => { Thread.Sleep(3000); return "Give me an error"; });它将正常工作.为什么不可能WebClient.DownloadStringTaskAsync在控制器的构造函数中使用该方法?