I need to call HttpWebRequest asynchronously, the problem is that BeginGetResponse method has as its first parameter AsyncCallback which targets method with void signature.
WebRequest _webRequest;
private void StartWebRequest()
{
_webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);
}
I need have as target method with Stream return type. Something like this:
private Stream FinishWebRequest(IAsyncResult result)
{
var response= _webRequest.EndGetResponse(result);
using (var stream = response.GetResponseStream())
{
Byte[] buffer = new Byte[response.ContentLength];
int offset = 0, actuallyRead = 0;
do
{
actuallyRead = stream.Read(buffer, offset, buffer.Length - offset);
offset += actuallyRead;
}
while (actuallyRead > 0);
return new MemoryStream(buffer);
}
}
How can I achieve this?
You can’t, basically. That can’t be your callback. Moreover, it would be pointless for it to be your callback, because nothing could actually use the returned stream. What are you intending to happen with the stream once the callback has fired?
It’s easy enough to create a callback which just calls your
FinishWebRequestmethod, but that would discard the stream, leaving you no better off…(Personally I wouldn’t rely on ContentLength by the way – it’s not always set. I’d just maintain a small buffer which you read into and then write straight into the memory stream. If you’re using .NET 4 you can use the new
Stream.CopyTomethod to make life easier. Also,WebResponseimplementsIDisposableso you should have ausingstatement for that too.)