页面加载需要永远

时间:2017-04-18 12:35:42

标签: c# asp.net-mvc

我有一个简单的方法:

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

在我的Index.cshtml中:

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

这让我永远等待!

2 个答案:

答案 0 :(得分:11)

这是一种僵局。

你正在使用.Result阻止当前线程并等待响应 - 而在async方法中,完成后 - 它会尝试返回到该线程但是  该线程已被阻止(由您的。Result)。

您应该async / await一直(或使用ConfigureAwait(false)

答案 1 :(得分:0)

您可以尝试ContinueWith方法,但我认为它会出错,因为asp.net中的SynchronizationContext并不那么容易。

不错的做法是:

控制器

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

查看:

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