目前正在使用cloud / azure和windows phone 7开展项目,我必须致电服务。
对我来说,方便我休息,但我遇到了问题; 我不知道我的上诉何时完成。
public static bool CreateUser(User userToCreate)
{
if (CheckNetwork())
{
var client = new RestClient(Global.Url);
var request = new RestRequest("/user", Method.POST);
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(User));
ser.WriteObject(ms, userToCreate);
string json = JsonHelper.ToJson(userToCreate);
request.AddHeader("Content-type", "application/json; charset=utf-8");
request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
try
{
object resp = null;
client.ExecuteAsync(request, response =>
{
if (response.ResponseStatus == ResponseStatus.Completed)
{
RestResponse resource = response;
string content = resource.Content;
resp = Convert.ToBoolean(JsonHelper.FromJson<string>(content));
}
});
return (bool)resp;
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
return false;
}
}
MessageBox.Show("You are not connect to the network!");
return false;
}
在此示例中,该方法在调用服务之前首先返回“resp”。 我怎么能确定在resp没有被填充之前我不退出这个方法?
答案 0 :(得分:7)
EventWaitHandle Wait = new AutoResetEvent(false);
client.ExecuteAsync(request, response =>
{
if (response.ResponseStatus == ResponseStatus.Completed)
{
RestResponse resource = response;
string content = resource.Content;
resp = Convert.ToBoolean(JsonHelper.FromJson<string>(content));
Wait.Set();
}
});
Wait.WaitOne();