Skip to content

Instantly share code, notes, and snippets.

@follesoe
Created March 14, 2012 15:06
Show Gist options
  • Save follesoe/2037102 to your computer and use it in GitHub Desktop.
Save follesoe/2037102 to your computer and use it in GitHub Desktop.
Async
public byte[] Get()
{
byte[] data = null;
var manualResetEvent = new ManualResetEvent(false);
var timedOut = false;
var req = CreateGetHttpWebRequest(Url);
try
{
if (Config.Debug)
LogRequest(req, null);
req.BeginGetResponse(asyncRequest => {
if (timedOut) return;
var request = (HttpWebRequest)asyncRequest.AsyncState;
var response = request.EndGetResponse(asyncRequest);
using (var streamResponse = response.GetResponseStream())
{
data = streamResponse.ReadFully();
manualResetEvent.Set();
}
response.Close();
}, req);
}
catch (WebException e)
{
throw new ConnectionException(e.Message, e);
}
var signaled = manualResetEvent.WaitOne(HttpRequestTimeout);
if (!signaled)
{
timedOut = true;
throw new ConnectionException(Strings.ConnectionErrorMessage, null);
}
if (Config.Debug)
LogResponse(data.Length + " bytes");
return data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment