问题描述
publicdelegatevoidGetResultEventHandler(objectsender,boolIsSucceed,stringDataResults);publiceventGetResultEventHandlerOnGetInfoCompleted;publicvoidGetPostHtmlResults(stringGetURL,intGetTimeOut){HttpWebRequestrequest=HttpWebRequest.CreateHttp(GetURL);request.Method="GET";request.ContinueTimeout=GetTimeOut;request.BeginGetResponse(GetInfoCompleted,request);}privatevoidGetInfoCompleted(IAsyncResultasyncResult){try{HttpWebRequestwebRequest=asyncResult.AsyncStateasHttpWebRequest;HttpWebResponsewebResponse=(HttpWebResponse)webRequest.EndGetResponse(asyncResult);StreamstreamResult=webResponse.GetResponseStream();StreamReaderreader=newStreamReader(streamResult,Encoding.UTF8);if(OnGetInfoCompleted!=null)OnGetInfoCompleted(this,true,reader.ReadToEnd());}catch(WebExceptionex){OnGetInfoCompleted(this,false,ex.Message.ToString());}}请问这个同/异步委托对不对,还有怎样调用它,谢谢!
解决方案
解决方案二:
.NET4.5异步编程强大啊,你可以用HttpClient类。
解决方案三:
用这个publicclassHttpHelper{privatestaticreadonlystringDefaultUserAgent="Mozilla/5.0(Windows;U;WindowsNT5.1;zh-CN;rv:1.8.1.16)Gecko/20080702Firefox/2.0.0.16";///<summary>///创建POST方式的HTTP请求///</summary>///<paramname="url">请求的URL</param>///<paramname="parameters">随同请求POST的参数名称及参数值字典</param>///<paramname="userAgent">请求的客户端浏览器信息,可以为空</param>///<paramname="requestEncoding">发送HTTP请求时所用的编码</param>///<paramname="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>///<returns></returns>publicstaticTask<WebResponse>CreatePostHttpResponse(stringurl,IDictionary<string,string>parameters,stringuserAgent,EncodingrequestEncoding,CookieContainercookieContainer){if(string.IsNullOrEmpty(url)){thrownewArgumentNullException("url");}if(requestEncoding==null){thrownewArgumentNullException("requestEncoding");}HttpWebRequestrequest=WebRequest.Create(url)asHttpWebRequest;request.Method="POST";request.ContentType="application/x-www-form-urlencoded";if(!string.IsNullOrEmpty(userAgent)){request.UserAgent=userAgent;}else{request.UserAgent=DefaultUserAgent;}if(cookieContainer==null){request.CookieContainer=newCookieContainer();}else{request.CookieContainer=cookieContainer;}//如果需要POST数据if(!(parameters==null||parameters.Count==0)){StringBuilderbuffer=newStringBuilder();inti=0;foreach(stringkeyinparameters.Keys){if(i>0){buffer.AppendFormat("&{0}={1}",key,parameters[key]);}else{buffer.AppendFormat("{0}={1}",key,parameters[key]);}i++;}byte[]data=requestEncoding.GetBytes(buffer.ToString());vartask=Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream,request.EndGetRequestStream,request,TaskCreationOptions.None);//等待任务完成task.Wait();//执行完本任务后再连续执行写入留和返回response对象'using(Streamstream=task.Result)//如果上面没有等待任务完成那一句,在这里直接获取结果也是可以的{stream.Write(data,0,data.Length);}}returnTask.Factory.FromAsync<WebResponse>(request.BeginGetResponse,request.EndGetResponse,request,TaskCreationOptions.None);}///<summary>///创建GET方式的HTTP请求///</summary>///<paramname="url">请求的URL</param>///<paramname="timeout">请求的超时时间</param>///<paramname="userAgent">请求的客户端浏览器信息,可以为空</param>///<paramname="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>///<returns></returns>publicstaticTask<WebResponse>CreateGetHttpResponse(stringurl,stringuserAgent,CookieContainercookieContainer){if(string.IsNullOrEmpty(url)){thrownewArgumentNullException("url");}HttpWebRequestrequest=WebRequest.Create(newUri(url))asHttpWebRequest;request.Method="GET";request.UserAgent=DefaultUserAgent;if(!string.IsNullOrEmpty(userAgent)){request.UserAgent=userAgent;}if(cookieContainer==null){request.CookieContainer=newCookieContainer();}else{request.CookieContainer=cookieContainer;}returnTask.Factory.FromAsync<WebResponse>(request.BeginGetResponse,request.EndGetResponse,request,TaskCreationOptions.None);}}
然后结合synchronizationcontext使用就ok了