我试图将来自 webclient 的响应转换为 Json,但它试图在从服务器下载它之前创建 JSON 对象。有没有一种“好”的方式让我等待 WebOpenReadCompleted 被执行?
不得不提的是,这是一个 WP7 应用,所以一切都是异步的
public class Client
{
public String _url;
private String _response;
private WebClient _web;
private JObject jsonsobject;
private Boolean blockingCall;
private Client(String url)
{
_web = new WebClient();
_url = url;
}
public JObject Login(String username, String password)
{
String uriUsername = HttpUtility.UrlEncode(username);
String uriPassword = HttpUtility.UrlEncode(password);
Connect(_url + "/data.php?req=Login&username=" + uriUsername + "&password=" + uriPassword + "");
jsonsobject = new JObject(_response);
return jsonsobject;
}
public JObject GetUserInfo()
{
Connect(_url + "/data.php?req=GetUserInfo");
jsonsobject = new JObject(_response);
return jsonsobject;
}
public JObject Logout()
{
Connect(_url + "/data.php?req=Logout");
jsonsobject = new JObject(_response);
return jsonsobject;
}
private void Connect(String url)
{
_web.Headers["Accept"] = "application/json";
_web.OpenReadCompleted += new OpenReadCompletedEventHandler(WebOpenReadCompleted);
_web.OpenReadAsync(new Uri(url));
}
private void WebOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error != null || e.Cancelled)
{
MessageBox.Show("Error:" + e.Error.Message);
_response = "";
}
else
{
using (var reader = new StreamReader(e.Result))
{
_response = reader.ReadToEnd();
}
}
}
}