[英]WebRequest.BeginGetResponse -“AsyncCallback” target on non void method
我需要異步調用 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);
}
}
我怎樣才能做到這一點?
你不能,基本上。 那不可能是你的回調。 此外,將它作為您的回調將毫無意義,因為實際上沒有任何東西可以使用返回的流。 一旦回調被觸發,你打算對流發生什么?
創建一個只調用您的FinishWebRequest
方法的回調很容易,但這會丟棄流,讓您沒有更好的...
(就我個人而言,順便說一下,我不會依賴 ContentLength - 它並不總是設置。我只是維護一個小緩沖區,您可以將其讀入然后直接寫入內存流。如果您使用的是 .NET 4,您可以使用新的Stream.CopyTo
方法讓生活更輕松。此外, WebResponse
實現了IDisposable
所以你也應該有一個using
語句。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.