I've been building a small Portable Class Library and it makes use of the WebRequest class. I'm targeting .Net 4.0 (and above), Silverlight 5 and Windows App Store. I would target the phone as well but it doesn't support the TPL at the moment - WP8 is just around the corner:
I wanted to use async method GetRequestStreamAsync & GetResponseAsync but these aren't supported in .Net 4.0 and when creating a Portable Class Library you only get the commonly supported methods across the configured platforms - so no support then or may be not...
Why not just create a couple of extension methods?
When used with the AsyncBridge NuGet package to provide async support in .Net 4.0 \ Silverlight 5 you get exactly the same syntax as if this was a standard .Net 4.5 library:
I wanted to use async method GetRequestStreamAsync & GetResponseAsync but these aren't supported in .Net 4.0 and when creating a Portable Class Library you only get the commonly supported methods across the configured platforms - so no support then or may be not...
Why not just create a couple of extension methods?
1: public static class HttpWebRequestExtensions
2: {
3: public static Task<Stream> GetRequestStreamAsync(this HttpWebRequest request)
4: {
5: var tcs = new TaskCompletionSource<Stream>();
6:
7: try
8: {
9: request.BeginGetRequestStream(iar =>
10: {
11: try
12: {
13: var response = request.EndGetRequestStream(iar);
14: tcs.SetResult(response);
15: }
16: catch (Exception exc)
17: {
18: tcs.SetException(exc);
19: }
20: }, null);
21: }
22: catch (Exception exc)
23: {
24: tcs.SetException(exc);
25: }
26:
27: return tcs.Task;
28: }
29:
30: public static Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request)
31: {
32: var tcs = new TaskCompletionSource<HttpWebResponse>();
33:
34: try
35: {
36: request.BeginGetResponse(iar =>
37: {
38: try
39: {
40: var response = (HttpWebResponse)request.EndGetResponse(iar);
41: tcs.SetResult(response);
42: }
43: catch (Exception exc)
44: {
45: tcs.SetException(exc);
46: }
47: }, null);
48: }
49: catch (Exception exc)
50: {
51: tcs.SetException(exc);
52: }
53:
54: return tcs.Task;
55: }
56: }
When used with the AsyncBridge NuGet package to provide async support in .Net 4.0 \ Silverlight 5 you get exactly the same syntax as if this was a standard .Net 4.5 library:
Comments
Post a Comment