Question

I'm working on my personal website and I have a gallery in which I need to implement a preloader. In order to test, I decided to make my own .ashx handler to test image loading (with a simple Thread.Sleep() for simulating network delay) but Firefox does not display them one by one as they finish loading, but all at once. It's weird since where the images are to be shown there are no tables, only divs, so they should show up on-the-fly.

In random cases though, it shows, let's say, 3, and then the other 2 (let's assume I have 5 images) show up. I'd like them to load in random intervals, but I dunno what could be wrong in my code.

Here's my .ashx code:

<%@ WebHandler Language="C#" Class="GetImg" %>
using System.IO;
using System.Web;
using System.Text;

public class GetImg : IHttpHandler
{
    public bool IsReusable { get { return true; } }

    public void ProcessRequest(HttpContext ctx)
    {
        System.Threading.Thread.Sleep(new System.Random((int)System.DateTime.Now.Ticks).Next(5) * 1000);
        ctx.Response.ContentType = "image/jpg";
        ctx.Response.BinaryWrite(File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/test.jpg")));
    }
}

Thanks in advance for all the help you guys can provide :)

Was it helpful?

Solution

Your browsers starts downloading images in parallel; there's no reason to wait for first image to ask for the second one!

Your webserver, too, starts a session (and a thread) for each request. So, both sessions start in the same second, and wait 5*1000 together... and send response at the same moment.

You can think some kind of trick:
- realize a queue in the server (using Context.Application to make Threads communicate each other), so that images can be served in sequence
- use a random number instead of System.DateTime.Now.Ticks to have random delay

but the actual behaviour is emulating a real situation of many images served by a server with same delay time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top