WebRequest.BeginGetResponse -“AsyncCallback”目标为非空方法
我需要异步调用 HttpWebRequest,问题是 BeginGetResponse 方法的第一个参数 AsyncCallback 目标为带有 void 签名的方法。
WebRequest _webRequest;
private void StartWebRequest()
{
_webRequest.BeginGetResponse(new AsyncCallback(FinishWebRequest), null);
}
我需要具有 Stream 返回类型的目标方法。像这样的事情:
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);
}
}
我怎样才能实现这个目标?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
基本上你不能。那不可能是你的回调。此外,它作为您的回调是毫无意义的,因为没有任何东西可以实际使用返回的流。回调触发后,您打算对流进行什么处理?
创建一个只调用 FinishWebRequest 方法的回调非常简单,但这会丢弃流,让您没有更好的情况......
(顺便说一句,我个人不会依赖 ContentLength - 它是并不总是设置。我只是维护一个小的缓冲区,您可以将其读入,然后直接写入内存流。如果您使用的是 .NET 4,则可以使用新的
Stream.CopyTo
方法让生活更轻松。另外,WebResponse
实现了IDisposable
,因此您也应该有一个using
语句。)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
FinishWebRequest
method, 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.CopyTo
method to make life easier. Also,WebResponse
implementsIDisposable
so you should have ausing
statement for that too.)