I have a very simple ASP.NET MVC 4 controller:
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); } } When I start the project I see my view and it looks fine, but when I update the page I get the following error:
[InvalidOperationException: An asynchronous module or handler completed while an asynchronous operation was still pending.]
Why does it happen? I made a couple of tests:
- If we remove
task = DownloadAsync();from the constructor and put it into theIndexmethod it will work fine without the errors. - If we use another
DownloadAsync()bodyreturn await Task.Factory.StartNew(() => { Thread.Sleep(3000); return "Give me an error"; });it will work properly.
Why it is impossible to use the WebClient.DownloadStringTaskAsync method inside a constructor of the controller?