{"id":156,"date":"2014-06-28T18:07:34","date_gmt":"2014-06-28T16:07:34","guid":{"rendered":"http:\/\/dev.bratched.fr\/en\/?p=156"},"modified":"2014-06-28T18:07:34","modified_gmt":"2014-06-28T16:07:34","slug":"http-and-images-in-windows-phone","status":"publish","type":"post","link":"https:\/\/bratched.com\/en\/2014\/06\/28\/http-and-images-in-windows-phone\/","title":{"rendered":"HTTP and images in Windows Phone"},"content":{"rendered":"<p>I continue to explore different techniques of displaying images in Windows Phone and this time I will show some possible implementations of fetching them from the web using the HTTP protocol.<\/p>\n<h1>Classic implementation:<\/h1>\n<pre class=\"lang:default decode:true\">public static void GethttpImage1(string urlImage, Action&lt;BitmapImage&gt; action)  \n{\n  var request = (HttpWebRequest)WebRequest.Create(urlImage);\n  request.BeginGetResponse(result =&gt;\n  {\n    using (var sr = request.EndGetResponse(result))\n    {\n        Deployment.Current.Dispatcher.BeginInvoke(() =&gt;\n            {\n                var image = new BitmapImage();\n                image.SetSource(sr.GetResponseStream());\n                if (action != null)\n                    action(image);\n                sr.Close();\n            });\n    }\n  }\n}\n<\/pre>\n<p>urlImage is a string representation of the url of the image\u00a0: example\u00a0: <a href=\"http:\/\/dev.bratched.fr\/download\/testimage1.png\">http:\/\/dev.bratched.fr\/download\/testimage1.png<\/a><\/p>\n<p>This method uses the WebRequest class and reads the response as a Stream using request.EndGetResponse.<\/p>\n<p>The<\/p>\n<pre class=\"lang:default decode:true\">Deployment.Current.Dispatcher.BeginInvoke(() =&gt;\n<\/pre>\n<p>call is very important as it allows us to use the BitmapImage on the main UI thread even when the callback is invoked on a background thread.<\/p>\n<p>The method will invoke the action and pass the retrieved image to this action as parameter.<\/p>\n<p>It can be invoked like this in order to set a property of type BitmapImage:<\/p>\n<pre class=\"lang:default decode:true\">HttpImageService.GethttpImage1(\"http:\/\/dev.bratched.fr\/download\/testimage1.png\", b =&gt;\n    {\n       Image = b;\n    });<\/pre>\n<h1>Implementation with async\/await:<\/h1>\n<p>The &#8220;Microsoft Async&#8221; allows to use the async\/await pattern in the standard Windows Phone methods.<\/p>\n<p><a href=\"http:\/\/dev.bratched.fr\/fr\/wp-content\/uploads\/sites\/2\/2014\/06\/NuGetPackagesAsync.jpg\"><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-652\" src=\"http:\/\/dev.bratched.fr\/fr\/wp-content\/uploads\/sites\/2\/2014\/06\/NuGetPackagesAsync.jpg\" alt=\"NuGetPackagesAsync\" width=\"829\" height=\"560\" \/><\/a><\/p>\n<p>This package adds some extension methods to the standard WebRequest class returning Task&lt;BitmapImage&gt;<\/p>\n<pre class=\"lang:default decode:true\">using (WebResponse response = await request.GetResponseAsync())<\/pre>\n<p>&nbsp;<\/p>\n<p>Replaces the following elements:<\/p>\n<pre class=\"lang:default decode:true\">request.BeginGetResponse(result =&gt;\n  {\n    using (var sr = request.EndGetResponse(result))\n    {<\/pre>\n<p>The function returns directly a Task&lt;BitmapImage&gt; instead of passing an action as parameter<\/p>\n<pre class=\"lang:default decode:true\">public static async Task&lt;BitmapImage&gt; GethttpImage2(string urlImage)\n{\n    try\n    {\n        var request = (HttpWebRequest)WebRequest.Create(urlImage);\n        using (WebResponse response = await request.GetResponseAsync())\n        {\n            BitmapImage image = null;\n            DispatcherSynchronizationContext dsc = new DispatcherSynchronizationContext(Deployment.Current.Dispatcher);\n            await Task.Factory.StartNew(() =&gt;\n            {\n                dsc.Send(_ =&gt;\n                {\n                    image = new BitmapImage();\n                    image.SetSource(response.GetResponseStream());\n                }, null);\n            });\n            return image;\n        }\n    }\n    catch (Exception)\n    {\n        return null;\n    }\n}\n<\/pre>\n<p>Remark\u00a0:<\/p>\n<pre class=\"lang:default decode:true\">DispatcherSynchronizationContext dsc = new DispatcherSynchronizationContext(Deployment.Current.Dispatcher);\n            await Task.Factory.StartNew(() =&gt;\n            {\n                dsc.Send(_ =&gt;\n                {\n<\/pre>\n<p>replaces<\/p>\n<pre class=\"lang:default decode:true\">Deployment.Current.Dispatcher.BeginInvoke(() =&gt;<\/pre>\n<p>Here we still need to marshal the call on the main Thread to allow using the returned BitmapImage and bind it on the UI.<\/p>\n<p>The async\/await pattern illustrated here allows better management of the threads as it relies on the TPL. Vous pouvez la remplacer sans soucis par l\u2019ancien code.<\/p>\n<p>Here&#8217;s how you could call the function: (Image is a property of type BitmapImage)<\/p>\n<pre class=\"lang:default decode:true\">Image = await HttpImageService.GethttpImage2(\"http:\/\/dev.bratched.fr\/download\/testimage1.png\");\n<\/pre>\n<h1>HttpClient<\/h1>\n<p>The &#8220;Microsoft\u00a0HTTP Client Libraries&#8221; NuGet needs to be installed in order to be able to use the HttpClient class. The advantage of this class is that it allows to use the same syntax as we would in a Windows 8 application.<\/p>\n<p><a href=\"http:\/\/dev.bratched.fr\/fr\/wp-content\/uploads\/sites\/2\/2014\/06\/NuGetPackageshttpClient.jpg\"><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-653\" src=\"http:\/\/dev.bratched.fr\/fr\/wp-content\/uploads\/sites\/2\/2014\/06\/NuGetPackageshttpClient.jpg\" alt=\"NuGetPackageshttpClient\" width=\"813\" height=\"516\" \/><\/a><\/p>\n<p>Important remark: it&#8217;s necessary to use a buffer instead of a Stream because<\/p>\n<ul>\n<li>BitmapImage needs to be used on the main Thread<\/li>\n<li>The Main thread cannot be used in AsyncStream<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<pre class=\"lang:default decode:true\">public static async Task&lt;BitmapImage&gt; GethttpImage3(string urlImage)\n{\n    try\n    {\n\n        HttpClient httpClient = new HttpClient() { MaxResponseContentBufferSize = 100000000 };\n        var ImageData = await httpClient.GetByteArrayAsync(urlImage);\n        {\n            using (var s = new MemoryStream(ImageData))\n            {\n                BitmapImage image = null;\n                DispatcherSynchronizationContext dsc = new DispatcherSynchronizationContext(Deployment.Current.Dispatcher);\n                await Task.Factory.StartNew(() =&gt;\n                {\n                    dsc.Send(_ =&gt;\n                    {\n                        image = new BitmapImage();\n                        image.SetSource(s);\n                    }, null);\n                });\n                return image;\n            }\n        }\n    }\n    catch\n    {\n        return null;\n    }\n}\n\n<\/pre>\n<p>This function can be called the same way as before:<\/p>\n<pre class=\"lang:default decode:true\">Image = await HttpImageService.GethttpImage3(\"http:\/\/dev.bratched.fr\/download\/testimage1.png\");<\/pre>\n<h1>Performance tests<\/h1>\n<p>The 3 methods can be used but which one performs better when loading multiple images?<\/p>\n<p>I have adapted the previous program from <a title=\"Utilisation des Images resources avec Windows Phone\" href=\"http:\/\/dev.bratched.fr\/fr\/utilisation-des-images-resources-avec-windows-phone\/\">Performance tests of static images<\/a> to<\/p>\n<ul>\n<li>Display the 3 methods in the lists<\/li>\n<li>Benchmark by loading 10 times the big png image (400K 1000&#215;1000) from the previous article<\/li>\n<\/ul>\n<p>I have also added the MemoryCounter from Coding4Fun to follow the memory usage.<\/p>\n<p>Here are the results from a WiFi network (average from 20 passes).<\/p>\n<ul>\n<li>Method 1\u00a0: HttpRequest\/Response with Action callback\u00a0: <span style=\"color: #00ff00\">6 sec<\/span><\/li>\n<li>Method 2 : Async HttpRequest\/Response\u00a0: <span style=\"color: #ff0000\">9 sec<\/span><\/li>\n<li>Method 3\u00a0: HttpClient\u00a0: <span style=\"color: #ff9900\">8,5 sec<\/span><\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<p>During the tests I have also inverted the order of passes to avoid influencing the results.<\/p>\n<p>La consultation des listes donne un r\u00e9el aper\u00e7u des 3 diff\u00e9rentes m\u00e9thodes.<\/p>\n<p>C&#8217;est encore une fois la m\u00e9thode &#8220;classique&#8221; avec HttpRequest qui donne le meilleur r\u00e9sultat.<\/p>\n<p>Le syst\u00e8me d&#8217;Action permet d\u2019\u00e9viter l&#8217;attente de la fin du traitement du thread pour interroger le r\u00e9seau et permet ainsi une meilleure parall\u00e9lisassions des t\u00e2ches.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I continue to explore different techniques of displaying images in Windows Phone and this time I will show some possible implementations of fetching them from the web using the HTTP protocol. Classic implementation: public static void GethttpImage1(string urlImage, Action&lt;BitmapImage&gt; action) { var request = (HttpWebRequest)WebRequest.Create(urlImage); request.BeginGetResponse(result =&gt; { using (var sr = request.EndGetResponse(result)) { Deployment.Current.Dispatcher.BeginInvoke(() [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[269],"tags":[276,278,279,281,294,295],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/bratched.com\/en\/wp-json\/wp\/v2\/posts\/156"}],"collection":[{"href":"https:\/\/bratched.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/bratched.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/bratched.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/bratched.com\/en\/wp-json\/wp\/v2\/comments?post=156"}],"version-history":[{"count":0,"href":"https:\/\/bratched.com\/en\/wp-json\/wp\/v2\/posts\/156\/revisions"}],"wp:attachment":[{"href":"https:\/\/bratched.com\/en\/wp-json\/wp\/v2\/media?parent=156"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/bratched.com\/en\/wp-json\/wp\/v2\/categories?post=156"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/bratched.com\/en\/wp-json\/wp\/v2\/tags?post=156"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}