Skip to content

Instantly share code, notes, and snippets.

@biac
Created November 27, 2012 00:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save biac/4151506 to your computer and use it in GitHub Desktop.
Save biac/4151506 to your computer and use it in GitHub Desktop.
WP8 で WebRequest を使うとき、GetResponse() を await したいよね!
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);
});
}
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