Page loading forever

I have a simple method:

public async Task<List<Steam>> Get() { ObjectResult result = new Models.ObjectResult(); using (HttpClient client = new HttpClient()) { var Object = await client.GetAsync("http://api.steampowered.com/ISteamApps/GetAppList/v0001/"); if (Object != null) { JObject steamobject = JObject.Parse(Object.ToString()); var item = steamobject.SelectToken("applist").SelectToken("apps"); result = JsonConvert.DeserializeObject<ObjectResult>(item.ToString()); } } return result.MyList; } 

in my Index.cshtml:

  SteamGet getter = new SteamGet(); List<Steam> Games = getter.Get().Result; foreach (var item in Games) { <li> @item.Name </li> } 

It makes me wait forever!

+5
source share
2 answers

This is a dead end.

You are using .Result , which blocks the current thread and waits for a response - while in the async method, after completion - it tries to return to this thread, but this thread is already blocked (by your. Result ).

You must async / await completely (or use ConfigureAwait(false) )

+11
source

You can try ContinueWith , but I think it will be a mistake, because SynchronizationContext in asp.net is not so simple.

Good practice:

controller

 public async Task<List<Steam>> Get() { ObjectResult result = new Models.ObjectResult(); using (HttpClient client = new HttpClient()) { var Object = await client.GetAsync("http://api.steampowered.com/ISteamApps/GetAppList/v0001/"); if (Object != null) { JObject steamobject = JObject.Parse(Object.ToString()); var item = steamobject.SelectToken("applist").SelectToken("apps"); result = JsonConvert.DeserializeObject<ObjectResult>(item.ToString()); } } SteamGet getter = new SteamGet(); ViewBag.Games = await getter.Get(); return result.MyList; } 

View:

 foreach (var item in (Viewag.Games as List<Steam>)) { <li> @item.Name </li> } 
0
source

Source: https://habr.com/ru/post/1266853/


All Articles