Created
May 26, 2016 19:35
-
-
Save mantzas/5a7d9e78f656577cb727a145d4239168 to your computer and use it in GitHub Desktop.
Deadlock example on ASP.NET MVC Controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class HomeController : Controller | |
{ | |
public ActionResult Index() | |
{ | |
var jsonTask = GetJsonDeadLockAsync(new Uri("http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo")); | |
//var jsonTask = GetJsonAsync(new Uri("http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo")); | |
var result = jsonTask.Result.ToString(); // this here blocks the initial thread along with it's context | |
return View(); | |
} | |
public static async Task<JObject> GetJsonAsync(Uri uri) | |
{ | |
using (var client = new HttpClient()) | |
{ | |
var jsonString = await client.GetStringAsync(uri).ConfigureAwait(false); | |
return JObject.Parse(jsonString); | |
} | |
} | |
public static async Task<JObject> GetJsonDeadLockAsync(Uri uri) | |
{ | |
using (var client = new HttpClient()) | |
{ | |
var jsonString = await client.GetStringAsync(uri); //when returning here it waits for the context to be available. Deadlock! | |
return JObject.Parse(jsonString); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment