如何异步使用HttpWebRequest(.NET)?如何异步使用HttpWebRequest(.NET,C#)?
3 回答
莫回无
TA贡献1865条经验 获得超7个赞
HttpWebRequest.BeginGetResponse()
HttpWebRequest webRequest;void StartWebRequest(){ webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);}void FinishWebRequest(IAsyncResult result){ webRequest.EndGetResponse(result);}
EndGetResponse()
慕慕森
TA贡献1856条经验 获得超17个赞
HttpWebRequest webRequest;void StartWebRequest(){ webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);}void FinishWebRequest(IAsyncResult result){ webRequest.EndGetResponse(result);}
void StartWebRequest(){ HttpWebRequest webRequest = ...; webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), webRequest);}void FinishWebRequest(IAsyncResult result){ HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;}
弑天下
TA贡献1818条经验 获得超8个赞
BeginGetResponse()
在此方法成为异步之前,BeginGetResponse方法需要完成一些同步设置任务(例如DNS解析、代理检测和TCP套接字连接)。因此,不应在用户界面(UI)线程上调用此方法,因为在引发错误或该方法成功之前,可能需要相当长的时间(取决于网络设置)来完成初始的同步设置任务。
void DoWithResponse(HttpWebRequest request, Action<HttpWebResponse> responseAction){ Action wrapperAction = () => { request.BeginGetResponse(new AsyncCallback((iar) => { var response = (HttpWebResponse)((HttpWebRequest)iar.AsyncState).EndGetResponse(iar); responseAction(response); }), request); }; wrapperAction.BeginInvoke(new AsyncCallback((iar) => { var action = (Action)iar.AsyncState; action.EndInvoke(iar); }), wrapperAction);}
HttpWebRequest request;// init your request...then:DoWithResponse(request, (response) => { var body = new StreamReader(response.GetResponseStream()).ReadToEnd(); Console.Write(body);});
- 3 回答
- 0 关注
- 1617 浏览
添加回答
举报
0/150
提交
取消