Reputation: 1709
Currently working on a project with the cloud / azure and windows phone 7, I must make a call to service.
For me the convenience I use sharp rest but I am facing a problem; I do not know when my appeal is complete.
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;
}
In this example, the method return first "resp" before making his call to service. How can I be sure I do not exit this method before resp not been filled?
Upvotes: 2
Views: 4376
Reputation: 8126
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();
Upvotes: 7