WP8中使用async/await扩展HttpWebRequest

前文讲到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
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

WP8中使用async/await扩展HttpWebRequest,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。