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.