如何编写异步方法?

时间:2011-03-02 19:48:37

标签: windows-phone-7 asynchronous

我有一个执行Http POST的方法,因为我正在使用HttpWebRequest来执行它,所以该方法依赖于异步调用。因为我需要我的方法来返回我的Http POST的响应代码,所以我想让我的方法异步。我该怎么做呢?

我在考虑使用Dispatcher。

编辑:所以我的代码结构的基本轮廓如下所示:

string response;

string httpPost(){
    HttpWebRequest.BeginGetRequestStream(new AsyncCallback(requestCallback), httpWebRequest);
    return response;
}

void requestCallback(IAsyncResult asyncResult){
     HttpWebRequest.EndGetRequestStream(asyncResult);
     HttpWebRequest.BeginGetResponse(new AsyncCallback(responseCallback), httpWebRequest);
}

void responseCallback(IAsyncResult asyncResult){
     HttpWebResponse webResponse = (HttpWebResponse) HttpWebRequest.EndGetResponse(asyncResult);
     response = webResponse.StatusCode.ToString();
}

我想将httpPost()更改为异步方法。

EDIT2:

public static void httpPost(Action<string> completed)
{        
    HttpWebRequest.BeginGetRequestStream(new AsyncCallback(requestCallback), httpWebRequest);
    completed(HttpEngine.response);
}

1 个答案:

答案 0 :(得分:1)

在WP7上,HTTPWebRequest已经是异步的 - 有关其使用示例,请参阅http://www.rudigrobler.net/blog/wp7-webclient-vs-httpwebrequest中的此代码

        public void DoThePost(Action<string> onSuccess)
{
     var request = (HttpWebRequest)WebRequest.Create(new Uri("http://www.sherdog.com/rss/news.xml"));
    request.BeginGetResponse(r =>
    {
            var httpRequest = (HttpWebRequest)r.AsyncState;
            var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(r);

            using (var reader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var response = reader.ReadToEnd();

                Deployment.Current.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        onSuccess(response);
                    }));
            }
    }, request);
}

跟:

DoPost((responseText) => { responseTextBlock.Text = responseText;});