所以这就是我想要做的和我已经完成的事情。
private static T _getjson<T>(string url) where T : new()
{
using (var w = new WebClient())
{
var json_data = string.Empty;
// attempt to download JSON data as a string
try
{
json_data = w.DownloadString(url);
}
catch (Exception) { }
// if string with JSON data is not empty, deserialize it to class and return its instance
return !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<T>(json_data) : new T();
}
}
此方法(调用时)的使用方式如下:
var onlineornot = ("http://blah.com");
var chatters = _getjson<Rootobject>(onlineornot);
<Rootobject>
是这样设置的类:
public class Rootobject
{
public _Links _links { get; set; }
public int chatter_count { get; set; }
public Chatters chatters { get; set; }
public Stream stream { get; set; }
public Stream game { get; set; }
public _Links2 _links2 { get; set; }
}
在大多数情况下,它可以正常工作,但每当我拨打_getJson
时,它都会导致我的应用挂起。我想知道如何在这种情况下使用Async,同时保持从<Rootobject>
获取属性的能力。
答案 0 :(得分:1)
快速回答,使用WebClient.DownloadStringAsync
方法:https://msdn.microsoft.com/en-us/library/ms144202(v=vs.110).aspx
像这样修改你的代码:
private static async Task<T> _getjson<T>(string url) where T : new()
{
using (var w = new WebClient())
{
var json_data = string.Empty;
// attempt to download JSON data as a string
try
{
json_data = await w.DownloadStringAsync(new Uri(url));
}
catch (Exception) { }
// if string with JSON data is not empty, deserialize it to class and return its instance
return !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<T>(json_data) : new T();
}
}
此外,关键是确保在主UI线程上不执行此操作。我不太了解您的申请,告诉您什么是适当的方法,但有很多帖子。
〜干杯
答案 1 :(得分:0)
WebClient
班级可以使用DownloadStringAsync()
方法(doc)。
Here是一篇简短的博文,展示了如何使用async
/ await
阻止您的用户界面阻止。
例如:
private static async Task<T> _getjson<T>(string url) where T : new()
{
using (var w = new WebClient())
{
var json_data = string.Empty;
// attempt to download JSON data as a string
try
{
json_data = await w.DownloadStringTaskAsync(url);
}
catch (Exception) { }
// if string with JSON data is not empty, deserialize it to class and return its instance
return !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<T>(json_data) : new T();
}
}
public async void Button1_Click(...)
{
...
var onlineornot = ("http://example.com");
var chatters = await _getjson<Rootobject>(onlineornot);
...
}