0

我有以下 C# 类,它启动从 Windows Phone 到服务器的 HTTP 请求:

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();
    }

现在,在我的主类中,我调用 doRequest 方法从 Windows Phone 发出 HTTP 请求:

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

调用此方法时,如何从服务器获取结果(结果变量),因为它是在 GetResponsetStreamCallback 方法中而不是在 doRequest 方法中接收的?

4

1 回答 1

0

你有几种可能性。一种是定义property使结果可以在外部访问。定义

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

您可能会创建一个事件并让对象订阅它,因此您可以在异步请求结束时注意到它们。或者让你的调用同步,这更容易做,因为你没有同步你的调用和来自其他对象的请求。

于 2013-04-17T13:08:49.153 回答