2

I am trying to read an image async from a web server. I works the first time, but after the next call the image just blinks and nothing happens.

I tried other approaches but I got the same result.

How can I update the image properly?

public async void ReadNextPhoto(Image image)
    {
        // getimage returns a random string with the image url
        var uri = new Uri("http://example.com/getimage.php");
        var httpClient = new HttpClient();

        // Always catch network exceptions for async methods
        try
        {
            var result = await httpClient.GetStringAsync(uri);

            var bi = new BitmapImage(new Uri(result));

            image.Source = bi;
        }
        catch
        {
            // Details in ex.Message and ex.HResult.       
        }

    }

Thank you, Jonathan

Edit: The answer from getimage.php is a string with the actual image example.com/random_image_01.jpg

Edit2: The problem is in the httpClient, it always returns the same string. Cache maybe?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Jonathan
  • 55
  • 6
  • What happens if you simply set `result` in the code to the actual image Url instead of loading it from the server? – miniBill Jun 01 '15 at 19:17
  • Because other apps use this service. Also, every time we access the service we get a different image string – Jonathan Jun 01 '15 at 20:03

1 Answers1

2

In HttpClient cache is enabled by default. As far as I know, the only way to get rid of it is to pass a random parameter, so it looks like a different request and it doesn't already exist in cache.

var uri = new Uri("http://example.com/getimage.php?no-cache=" & DateTime.Now.Ticks.ToString());
fillobotto
  • 3,698
  • 5
  • 34
  • 58
  • Awesome! Thank you sir! – Jonathan Jun 01 '15 at 22:17
  • Just a sidenote, we had these same caching issues, we managed to solve them using Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent. See post http://stackoverflow.com/questions/21643747/httpclient-every-time-returns-the-same-string – Andrei Hardau Jun 09 '15 at 12:17