1
我有一个执行Http POST的方法,并且由于我使用HttpWebRequest来执行它,所以该方法依赖于异步调用。由于我需要我的方法来返回我的Http POST的响应代码,我想让我的方法异步。我该怎么做呢?如何编写异步方法?
我正在考虑使用分派器。
编辑:所以我的代码结构的基本轮廓是这样的:
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);
}
我有一个方法为Http Post执行HttpWebRequest,但由于HttpWebRequest是异步,我想返回响应,我希望我的方法也是异步的。 – Hank
我认为你的编辑实际上让它不太清楚。如果您希望发生HTTP帖子时发生某些操作,请查看我所做的更改。 – Stuart
我想返回响应,但响应必须等到HTTP Post完成。这意味着当我以目前的形式调用该方法时,我不会得到响应,因为HTTP Post没有完成。假设我初始化响应为“开始”,当我调用httpPost时,它将返回“开始”而不是Web响应,因为HTTP Post没有完成。所以我想让httpPost方法异步并在另一个类中处理它。 – Hank