Question

I have the following C# class which initiates an HTTP request from a Windows Phone to a server:

public class Request
{
    public string data;
    public string result;

    public Request()
    {

    }

    public void doRequest(string parameters, string URL)
    {
        data = parameters;

        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
    }

    public void GetRequestStreamCallback(IAsyncResult callbackResult)
    {
        HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
        Stream postStream = myRequest.EndGetRequestStream(callbackResult);
        byte[] byteArray = Encoding.UTF8.GetBytes(data);

        postStream.Write(byteArray, 0, byteArray.Length);
        postStream.Close();

        myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
    }

    public void GetResponsetStreamCallback(IAsyncResult callbackResult)
    {
        HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);

        StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream());
        result = httpWebStreamReader.ReadToEnd();
    }

Now, in my main class, I call the doRequest method to do an HTTP request from the Windows Phone:

Request req = new Request();
req.doRequest("function=LogIn&username=" + username + "&password=" + password, "http://localhost:4000/Handler.ashx");

When calling this method, how can I get the result (the result variable) from the server since it is received in the GetResponsetStreamCallback method and not in the doRequest method?

Was it helpful?

Solution

You have several possibilities. One would be to define property to make the result accessible outside. Define

public class Request
{
    public string Result
    {
      get{ 
           if(result != null && !string.IsNullOrEmpty(result))
                return result;
           return null;
         }
    }
  ...
}

You might create an event and have objects subscribe to it, so you can notice them when the asynchronous request has ended. Or make your calls synchronous, which is a little easier to do, as you don't have synchronize your calls and the requests from other objects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top