Greta Porretta
Greta Porretta

Reputation: 99

Page loading takes 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>
        }

This makes me wait forever!

Upvotes: 5

Views: 189

Answers (2)

Royi Namir
Royi Namir

Reputation: 148524

This is a deadlock situation.

You're using .Result which blocks the current thread and waits for response - while in the async method , after finished — it tries to get back to that thread but that thread is already blocked ( by your .Result).

You should async/await all the way (or use ConfigureAwait(false))

Upvotes: 11

user4074041
user4074041

Reputation:

You can try ContinueWith method, but i think it will fault, because SynchronizationContext in asp.net not so easy.

Not bad practice is:

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>
        }

Upvotes: 0

Related Questions