Created
November 27, 2012 00:08
-
-
Save biac/4151506 to your computer and use it in GitHub Desktop.
WP8 で WebRequest を使うとき、GetResponse() を await したいよね!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static Task<WebResponse> GetResponseAsync(WebRequest request) | |
{ | |
return Task.Run<WebResponse>(() => | |
{ | |
AutoResetEvent autoResetEvent = new AutoResetEvent(false); | |
// BeginGetResponse で autoResetEvent を発火させる | |
IAsyncResult asyncResult = request.BeginGetResponse(r => autoResetEvent.Set(), null); | |
// autoResetEvent.Set() の発火を待つ。すなわちここでブロックする | |
autoResetEvent.WaitOne(); | |
return request.EndGetResponse(asyncResult); | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var uri = new Uri("http://hoge.moge..."); | |
string result; | |
var req = HttpWebRequest.Create(uri); | |
using (var res = await GetResponseAsync(req)) | |
using (var stream = res.GetResponseStream()) | |
using (var rdr = new StreamReader(stream)) | |
{ | |
result = await rdr.ReadToEndAsync(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment