0

I'm downloading some small images (about 40 KB each) in my MonoTouch app. The images are downloaded in parallel - the main thread creates the requests and executes them asynchronously.

I use WebRequest.Create to create the HTTP request, and in the completion handler, I retrieve the response stream using response.GetResponseStream(). Then, the following code reads the data from the response stream:

var ms = new MemoryStream();
byte[] buffer = new byte[4096];
int read;
while ((read = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
    ms.Write(buffer, 0, read);
}

When downloading only one image, this runs very fast (50-100 milliseconds, including the wait for the web request). However, as soon as there are several images, say 5-10, these lines need more than 2 seconds to complete. Sometimes the thread spends more than 4 second. Note that I'm not talking about the time needed for response.BeginGetResponse or the time waiting for the callback to run.

Then I tested the following code, it needs less than 100 milliseconds in the same scenario:

var ms = new MemoryStream();
responseStream.CopyTo(ms);

What's the reason for this huge lag in the first version?

The reason I need the first version of the code is that I need the partially downloaded data of the image (specially when the image is bigger). To isolate the performance problem, I removed the code which deals with the partially downloaded image.

I ran the code in Debug and Release mode in the simulator as well as on my iPad 3, and I tried both compiler modes, LLVM and non-LLVM. The lag was there in all configurations, Debug/Release, Device/Simulator, LLVM/non-LLVM.

4

2 回答 2

2

很可能是并发 http 网络连接数的限制:

http://msdn.microsoft.com/en-us/library/system.net.servicepoint.connectionlimit.aspx

于 2013-05-21T15:11:48.573 回答
0

您好,可能不是您问题的直接答案,但您是否尝试过Xamarin Component Store中的SDWebImage?这是一个由Olivier Poitrey开发的令人惊叹的库,开箱即用,提供异步图像下载器、内存 + 磁盘图像缓存和其他一些好处,真的很棒。

希望这可以帮助

亚历克斯

于 2013-05-14T15:37:51.743 回答