WP8中使用async/await扩展HttpWebRequest_移动开发_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > 移动开发 > WP8中使用async/await扩展HttpWebRequest

WP8中使用async/await扩展HttpWebRequest

 2014/4/4 11:36:16  刘白菜  博客园  我要评论(0)
  • 摘要:前文讲到WP8中使用Async执行HTTP请求,用了微软提供的扩展。下面提供了一种方法,自己实现HttpWebRequest的扩展。12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455namespaceHttpExtensions{publicstaticclassWebRequestExtensions
  • 标签:Web 使用 HttpWebRequest HTTP

前文讲到WP8中使用Async执行HTTP请求,用了微软提供的扩展。下面提供了一种方法,自己实现HttpWebRequest的扩展。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 class="csharp keyword">namespace HttpExtensions {     public static class WebRequestExtensions     {         public async static Task<WebResponse> GetResponseAsync(this HttpWebRequest request)         {             var tcs = new TaskCompletionSource<WebResponse>();               try             {                 request.BeginGetResponse((ar) =>                 {                     var response = request.EndGetResponse(ar);                     tcs.SetResult(response);                 }, null);             }             catch (WebException we)             {                 tcs.SetException(we);             }               return await tcs.Task;         }           public async static Task<WebResponse> GetResponseAsync(this HttpWebRequest request, string post)         {             var tcs = new TaskCompletionSource<WebResponse>();               try             {                 request.BeginGetRequestStream((arReq) =>                 {                     var stream = request.EndGetRequestStream(arReq);                     using (StreamWriter writer = new StreamWriter(stream))                     {                         writer.Write(post);                         writer.Flush();                     }                       request.BeginGetResponse((ar) =>                     {                         var response = request.EndGetResponse(ar);                         tcs.SetResult(response);                     }, null);                 }, null);             }             catch (WebException we)             {                 tcs.SetException(we);             }               return await tcs.Task;         }     } }

随后就可以使用 await HttpWebRequest.GetResponseAsync() 轻松使用http请求了。

 

原文http://blog.liubaicai.com/?p=280

发表评论
用户名: 匿名