<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
  <channel><title>Sergi Gisbert</title>
<description>Personal website - Sergi Gisbert | Software Architecht &amp; Developer</description>
<generator>Miniblog.Core</generator>
<link>https://www.sergigisbert.com/</link>
<item>
  <title>Optimizando la web: menos JavaScript, fuentes propias y un arranque en frío de segundos</title>
  <link>https://www.sergigisbert.com/blog/optimizando-la-web-menos-javascript-arranque-en-frio/</link>
  <description>&lt;p&gt;Cierro la serie sobre la puesta al d&amp;iacute;a de la web. Despu&amp;eacute;s de &lt;a title="De IIS a Azure Container Apps" href="/blog/de-iis-a-azure-container-apps-web-en-contenedor/"&gt;pasarla a Azure Container Apps&lt;/a&gt; y del &lt;a title="Redise&amp;ntilde;o de la web" href="/blog/rediseno-de-la-web-sistema-visual-propio/"&gt;redise&amp;ntilde;o visual&lt;/a&gt;, toca uno de mis temas favoritos desde hace a&amp;ntilde;os: el &lt;strong&gt;rendimiento&lt;/strong&gt; (WPO para los amigos). Ya escrib&amp;iacute; sobre &lt;a title="Optimizaci&amp;oacute;n de aplicaciones web: qu&amp;eacute; es y por qu&amp;eacute; es importante" href="/blog/optimizacion-de-aplicaciones-web-que-es-y-por-que-es-importante/"&gt;por qu&amp;eacute; es importante&lt;/a&gt;, as&amp;iacute; que esta vez vamos directos al grano.&lt;/p&gt;
&lt;h2&gt;Primero, medir&lt;/h2&gt;
&lt;p&gt;Nada de optimizar a ciegas. Antes de tocar una l&amp;iacute;nea med&amp;iacute; el TTFB de cada ruta con &lt;code&gt;curl&lt;/code&gt; y las m&amp;eacute;tricas de carga en el navegador (FCP, LCP, INP) con las DevTools y Lighthouse. Los dos problemas m&amp;aacute;s claros:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;El CSS de &lt;strong&gt;Google Fonts&lt;/strong&gt; bloqueaba el renderizado en todas las p&amp;aacute;ginas.&lt;/li&gt;
&lt;li&gt;La p&amp;aacute;gina de proyectos cargaba &lt;strong&gt;jQuery, Bootstrap JS y MixItUp&lt;/strong&gt; para filtrar 14 tarjetas, con un INP de unos &lt;strong&gt;230 ms&lt;/strong&gt; simulando una CPU 4 veces m&amp;aacute;s lenta.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Fuera el JavaScript que no hace nada&lt;/h2&gt;
&lt;p&gt;Tras el redise&amp;ntilde;o, el bundle de JavaScript de 2013 segu&amp;iacute;a carg&amp;aacute;ndose en todas las p&amp;aacute;ginas, aunque casi nada de &amp;eacute;l se usaba. Lo he ido quitando por partes:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;jQuery y Bootstrap JS&lt;/strong&gt;: eliminados. Lo poco que hac&amp;iacute;an (lazy load de im&amp;aacute;genes, bot&amp;oacute;n de "volver arriba") vive ahora en un &lt;code&gt;site.js&lt;/code&gt; peque&amp;ntilde;o y sin dependencias.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;AdSense&lt;/strong&gt;: su script solo se carga en las p&amp;aacute;ginas que realmente tienen un hueco de anuncio.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Google Analytics&lt;/strong&gt;: segu&amp;iacute;a cargando un script de Universal Analytics que no recoge datos desde 2024. Fuera. Para la anal&amp;iacute;tica b&amp;aacute;sica me basta Cloudflare Web Analytics.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Prism&lt;/strong&gt; (el resaltado de c&amp;oacute;digo que est&amp;aacute;s viendo) solo se carga en el blog.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;El caso m&amp;aacute;s claro es el filtro de proyectos. MixItUp, con sus animaciones, se ha sustituido por esto:&lt;/p&gt;
&lt;pre class="language-javascript"&gt;&lt;code&gt;filters.forEach(function (filter) {
    filter.querySelector('button').addEventListener('click', function () {
        var value = filter.getAttribute('data-filter');

        filters.forEach(function (f) {
            var on = f === filter;
            f.classList.toggle('active', on);
            f.querySelector('button').setAttribute('aria-pressed', on ? 'true' : 'false');
        });

        items.forEach(function (item) {
            item.hidden = value !== 'all' &amp;amp;&amp;amp; !item.classList.contains(value);
        });
    });
});&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Veinte l&amp;iacute;neas, accesible con &lt;code&gt;aria-pressed&lt;/code&gt; y, sin JavaScript, simplemente se ven todos los proyectos. El INP baja de ~230 ms a &lt;strong&gt;90-100 ms&lt;/strong&gt; en mis mediciones, la p&amp;aacute;gina pasa de 30 a &lt;strong&gt;17 peticiones&lt;/strong&gt; (161 KB en total) y Lighthouse le da un &lt;strong&gt;99&lt;/strong&gt;.&lt;/p&gt;
&lt;h2&gt;Fuentes propias, compresi&amp;oacute;n y cach&amp;eacute;&lt;/h2&gt;
&lt;p&gt;Las fuentes ahora se sirven desde la propia web: ficheros &lt;code&gt;woff2&lt;/code&gt; variables (un fichero para todos los pesos), solo con el subconjunto latino, &lt;code&gt;font-display: swap&lt;/code&gt; y un &lt;code&gt;preload&lt;/code&gt; de la fuente principal:&lt;/p&gt;
&lt;pre class="language-markup"&gt;&lt;code&gt;&amp;lt;link rel="preload" href="/fonts/schibsted-grotesk-latin.woff2" as="font" type="font/woff2" crossorigin /&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Revisando las cabeceras salieron dos detalles m&amp;aacute;s. El primero: el JavaScript minificado se serv&amp;iacute;a como &lt;code&gt;text/javascript&lt;/code&gt;, que no est&amp;aacute; en la lista por defecto de tipos comprimidos de ASP.NET Core, as&amp;iacute; que sal&amp;iacute;a sin comprimir. Lo mismo con los SVG:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
    new[] { "application/json", "text/javascript", "image/svg+xml" });&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;El segundo: las im&amp;aacute;genes del blog, guardadas en Azure Blob Storage, no llevaban ninguna cabecera de cach&amp;eacute;. Las nuevas se suben con &lt;code&gt;Cache-Control: public, max-age=31536000, immutable&lt;/code&gt;. Y la hoja de estilos se sirve ahora como &lt;code&gt;.css&lt;/code&gt; en lugar de &lt;code&gt;.scss&lt;/code&gt;, porque Cloudflare no cachea en el borde extensiones que no conoce.&lt;/p&gt;
&lt;h2&gt;El arranque en fr&amp;iacute;o: 28 segundos por un Task.Run&lt;/h2&gt;
&lt;p&gt;Esta es mi favorita. Con el contenedor escalando a cero, la primera visita tiene que esperar a que arranque, y al arrancar el blog carga todos sus posts desde Azure Blob Storage. Midiendo en local con la CPU limitada a 0,5 n&amp;uacute;cleos, esa carga tardaba &lt;strong&gt;unos 28 segundos&lt;/strong&gt;. El culpable:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;// Antes: parec&amp;iacute;a as&amp;iacute;ncrono, pero cada post bloqueaba un hilo
var tasks = blobs.Select(async file =&amp;gt;
{
    await LoadPost(posts, $"{blobUrl}/{this.blobContainer}/{file.Name}");
});
await Task.WhenAll(tasks);

protected static async Task LoadPost(ConcurrentBag&amp;lt;Post&amp;gt; cb, string file)
{
    await Task.Run(() =&amp;gt; cb.Add(ParsePost(XElement.Load(file), ...)));
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;XElement.Load(url)&lt;/code&gt; hace una petici&amp;oacute;n HTTP &lt;strong&gt;s&amp;iacute;ncrona&lt;/strong&gt;. Cada &lt;code&gt;Task.Run&lt;/code&gt; bloquea un hilo del &lt;em&gt;thread pool&lt;/em&gt; esperando la red, y con medio core el pool crece muy despacio, as&amp;iacute; que los posts acababan carg&amp;aacute;ndose casi uno a uno. La soluci&amp;oacute;n: usar el SDK de Azure en as&amp;iacute;ncrono de verdad.&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;// Ahora: descargas as&amp;iacute;ncronas con el SDK, sin bloquear hilos
var tasks = blobs.Select(async file =&amp;gt;
{
    using var stream = await _blobRepository.DownloadAsync(this.blobContainer, file.Name);
    posts.Add(ParsePost(XElement.Load(stream), Path.GetFileNameWithoutExtension(file.Name)));
});
await Task.WhenAll(tasks);&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;En local, de ~28 s a &lt;strong&gt;1,5-2 s&lt;/strong&gt;. Y ya en Azure, donde el contenedor y el Blob Storage est&amp;aacute;n en la misma red, la carga de posts se queda en &lt;strong&gt;~0,5 s&lt;/strong&gt;. Tiene su gracia, porque hace unos a&amp;ntilde;os escrib&amp;iacute; sobre &lt;a title="Utilizar ConcurrentBag para almacenar el resultado de m&amp;eacute;todos as&amp;iacute;ncronos" href="/blog/utilizar-concurrentbag-para-almacenar-el-resultado-de-metodos-asincronos/"&gt;usar ConcurrentBag con m&amp;eacute;todos as&amp;iacute;ncronos&lt;/a&gt;... y el &lt;code&gt;ConcurrentBag&lt;/code&gt; estaba bien. El problema era lo que hab&amp;iacute;a dentro de cada tarea :)&lt;/p&gt;
&lt;h2&gt;Que muchas visitas ni lleguen al contenedor&lt;/h2&gt;
&lt;p&gt;La &amp;uacute;ltima pieza est&amp;aacute; en Cloudflare: una regla de cach&amp;eacute; para el HTML de las p&amp;aacute;ginas localizadas (&lt;code&gt;/es...&lt;/code&gt; y &lt;code&gt;/en...&lt;/code&gt;) cuando la petici&amp;oacute;n no lleva cookies, con un TTL de varias horas en el borde. Las visitas que ya han aceptado las cookies o los administradores siguen yendo al origen, as&amp;iacute; que nadie ve una versi&amp;oacute;n equivocada. As&amp;iacute;, la home, los proyectos y la biograf&amp;iacute;a se sirven casi siempre desde Cloudflare y apenas sufren el arranque en fr&amp;iacute;o. El blog todav&amp;iacute;a no entra en la regla, porque su idioma de interfaz depende de la cabecera &lt;code&gt;Accept-Language&lt;/code&gt;; eso queda pendiente.&lt;/p&gt;
&lt;p&gt;Una an&amp;eacute;cdota al probarlo: &lt;code&gt;Invoke-WebRequest&lt;/code&gt; de Windows PowerShell 5.1 descarta en silencio la cabecera &lt;code&gt;Cookie&lt;/code&gt; si la pasas en &lt;code&gt;-Headers&lt;/code&gt;. Mis pruebas "con cookie" sal&amp;iacute;an cacheadas y no entend&amp;iacute;a nada hasta que cambi&amp;eacute; a &lt;code&gt;curl.exe&lt;/code&gt;:&lt;/p&gt;
&lt;pre class="language-powershell"&gt;&lt;code&gt;curl.exe -sI -b '.AspNet.Consent=yes' https://www.sergigisbert.com/es | Select-String cf-cache-status&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;El papel de la IA&lt;/h2&gt;
&lt;p&gt;Todo este trabajo lo he hecho con &lt;a title="Claude Code" href="https://claude.com/claude-code" target="_blank" rel="noopener"&gt;Claude Code&lt;/a&gt;, y aqu&amp;iacute; es donde m&amp;aacute;s se ha notado. Medir, cambiar, volver a medir y comparar es un bucle tedioso que la IA ejecuta muy bien: lanzar &lt;code&gt;curl&lt;/code&gt; contra cada ruta, abrir el navegador, sacar las m&amp;eacute;tricas y comparar las p&amp;aacute;ginas HTML antes y despu&amp;eacute;s para confirmar que nada hab&amp;iacute;a cambiado. El orden siempre el mismo: medir primero, atacar lo que m&amp;aacute;s pesa y verificar cada paso.&lt;/p&gt;
&lt;p&gt;Tambi&amp;eacute;n tiene sus l&amp;iacute;mites, claro: el diagn&amp;oacute;stico del &lt;em&gt;thread pool&lt;/em&gt; sali&amp;oacute; de medir con la CPU limitada como en producci&amp;oacute;n, no de una intuici&amp;oacute;n. Y cada bloque de cambios ha llegado a &lt;code&gt;main&lt;/code&gt; a trav&amp;eacute;s de su propia PR.&lt;/p&gt;
&lt;h2&gt;Conclusi&amp;oacute;n&lt;/h2&gt;
&lt;p&gt;Tres posts, una web nueva por dentro y por fuera: m&amp;aacute;s barata, con mejor aspecto y bastante m&amp;aacute;s r&amp;aacute;pida, sin haber reescrito la aplicaci&amp;oacute;n. La siguiente fase, que ya tengo en mente, es m&amp;aacute;s ambiciosa: dejar de lado el servidor y pasar a una web est&amp;aacute;tica. Pero eso, como siempre, ya ser&amp;aacute; otra historia...&lt;/p&gt;</description>
  <author>Sergi Gisbert</author>
  <category>claude code</category>
  <category>cloudflare</category>
  <category>javascript</category>
  <category>wpo</category>
  <category>performance</category>
  <category>personal</category>
  <guid isPermaLink="false">https://www.sergigisbert.com/blog/optimizando-la-web-menos-javascript-arranque-en-frio/</guid>
  <pubDate>Fri, 04 Dec 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Website redesign: goodbye Bootstrap 3, hello to my own visual system</title>
  <link>https://www.sergigisbert.com/blog/website-redesign-own-visual-system/</link>
  <description>&lt;p&gt;In the &lt;a title="From IIS to Azure Container Apps" href="/blog/from-iis-to-azure-container-apps-containerised-website/"&gt;previous post&lt;/a&gt; I explained how I moved the site into a container to pay a lot less. That part is invisible, but this one is not: the site had looked the same since 2013, with &lt;strong&gt;Bootstrap 3&lt;/strong&gt; and the &lt;strong&gt;Unify&lt;/strong&gt; template, links to social networks I no longer use and a good pile of CSS and JavaScript doing nothing at all. It was about time.&lt;/p&gt;
&lt;h2&gt;The rule: redesign without changing functionality&lt;/h2&gt;
&lt;p&gt;I set one condition from the start: &lt;strong&gt;the first step could not change anything functional&lt;/strong&gt;. Same routes, same controllers, same XML data. Only Razor views and styles. That way, if something broke, I knew the design was to blame and nothing else. Functional improvements (such as the blog language filter) came later, each in its own change.&lt;/p&gt;
&lt;p&gt;After that first pass, every main page (home, projects, biography and blog) got its own &lt;strong&gt;static HTML proposal&lt;/strong&gt; before being rebuilt: a mock-up you open in the browser, with real data and, in some cases, several options to compare. For the home page header, for example, three alternatives sat side by side before I picked the "editorial" one. Deciding is much easier when you are looking at something real rather than imagining a wireframe.&lt;/p&gt;
&lt;h2&gt;Tokens instead of a framework&lt;/h2&gt;
&lt;p&gt;Rather than swapping Bootstrap 3 for Bootstrap 5 (or Tailwind), I went for a single &lt;code&gt;site.scss&lt;/code&gt; of my own, built on &lt;strong&gt;CSS custom properties&lt;/strong&gt; (tokens). Every colour comes from them, and dark mode is just a matter of redefining those tokens with &lt;code&gt;prefers-color-scheme&lt;/code&gt;:&lt;/p&gt;
&lt;pre class="language-scss"&gt;&lt;code&gt;:root {
    --paper: #F4F6F7;
    --ink: #16232E;
    --muted: #556472;
    --accent: #0B5FA5;
    --accent-soft: #DCE8F3;
}

@media (prefers-color-scheme: dark) {
    :root {
        --paper: #0F1920;
        --ink: #E3E9ED;
        --muted: #98A7B2;
        --accent: #6EAEE6;
        --accent-soft: #1D3A52;
        color-scheme: dark;
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;No &lt;code&gt;.dark&lt;/code&gt; classes, no JavaScript and no flashing: the site simply follows the operating system preference. The logo, an "SG" monogram in SVG, is inlined in the header so it uses the tokens too and flips by itself in dark mode.&lt;/p&gt;
&lt;p&gt;For typography, two families: &lt;strong&gt;Schibsted Grotesk&lt;/strong&gt; for the UI and headings, and &lt;strong&gt;Source Serif 4&lt;/strong&gt; for the article body, which reads much better with a serif at a generous size. Both are self-hosted (more on that in the next post).&lt;/p&gt;
&lt;p&gt;A small gotcha: the project compiles SCSS with LibSass, which does not understand &lt;code&gt;clamp()&lt;/code&gt; and fails. The trick is to wrap it so it passes through untouched:&lt;/p&gt;
&lt;pre class="language-scss"&gt;&lt;code&gt;.hero h1 { font-size: #{unquote("clamp(36px, 4.6vw, 52px)")}; }&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Page by page&lt;/h2&gt;
&lt;p&gt;&lt;img src="https://sergiwebstorage.blob.core.windows.net/blogfiles/Posts/files/p2-home-desktop_639311535255309240.png" alt="The new home page" width="1280" height="800" /&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Home&lt;/strong&gt;: an editorial header with a photo, what I am doing now and the number of projects, followed by the latest articles.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Project timeline&lt;/strong&gt;: my favourite bit. A waterfall of projects since 2000, styled like the &lt;em&gt;Network&lt;/em&gt; tab in the browser DevTools. A nod for anyone who optimises websites for a living :)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src="https://sergiwebstorage.blob.core.windows.net/blogfiles/Posts/files/p2-timeline_639311536805165579.png" alt="Project timeline styled like the Network tab" width="1079" height="564" /&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Projects&lt;/strong&gt;: cards with a screenshot, dates and company, and filters grouped into "Type" and "Company" with a project count for each. On the detail page, a gallery with native &lt;code&gt;scroll-snap&lt;/code&gt;, thumbnails and keyboard navigation.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Biography&lt;/strong&gt;: it used to be tabs; now it is a single scroll with anchor navigation, and the details of each role folded into a &lt;code&gt;&amp;lt;details&amp;gt;&lt;/code&gt; so it does not drag on.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Blog&lt;/strong&gt;: posts listed by language with a link to each translation, reading time, a single-column article and "previous / next" cards.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src="https://sergiwebstorage.blob.core.windows.net/blogfiles/Posts/files/p2-projects-desktop_639311536809150388.png" alt="Project list with grouped filters" width="1280" height="800" /&gt;&lt;/p&gt;
&lt;p&gt;Some things also went away: the Twitter and Facebook links, the latest-tweets widget in the footer and the section index on the home page, which duplicated the menu. Less is more.&lt;/p&gt;
&lt;h2&gt;Checking every size (and colour)&lt;/h2&gt;
&lt;p&gt;Without a visual test suite, checking has been manual but systematic: every change reviewed on desktop and at &lt;strong&gt;375 px&lt;/strong&gt;, in light and dark mode. This is where AI helps again: with &lt;a title="Claude Code" href="https://claude.com/claude-code" target="_blank" rel="noopener"&gt;Claude Code&lt;/a&gt; driving a browser, I can ask it to open each page in all four combinations, take screenshots and flag overflows or odd contrast. It is like having someone do the boring QA while you decide whether the grey is too grey.&lt;/p&gt;
&lt;p&gt;&lt;img src="https://sergiwebstorage.blob.core.windows.net/blogfiles/Posts/files/p2-home-mobile-dark_639311536809371362.png" alt="The home page on mobile in dark mode" width="375" height="780" /&gt;&lt;/p&gt;
&lt;p&gt;The aesthetic judgement is still human, though. AI produces proposals fast, but many of them were "correct" and generic; the best ideas (like the DevTools-style timeline) came from iterating on them with a clear opinion of what I wanted.&lt;/p&gt;
&lt;h2&gt;Next up: performance&lt;/h2&gt;
&lt;p&gt;With the new design, much of the 2013 CSS and JavaScript was no longer used... but it was still loaded on every page. In the next and final post of the series I explain how I cleaned it up, removed jQuery completely and shortened the container's cold start.&lt;/p&gt;</description>
  <author>Sergi Gisbert</author>
  <category>claude code</category>
  <category>ux</category>
  <category>css</category>
  <category>frontend</category>
  <category>diseño</category>
  <category>personal</category>
  <category>english</category>
  <guid isPermaLink="false">https://www.sergigisbert.com/blog/website-redesign-own-visual-system/</guid>
  <pubDate>Mon, 30 Nov 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>Rediseño de la web: adiós a Bootstrap 3, hola a un sistema visual propio</title>
  <link>https://www.sergigisbert.com/blog/rediseno-de-la-web-sistema-visual-propio/</link>
  <description>&lt;p&gt;En el &lt;a title="De IIS a Azure Container Apps" href="/blog/de-iis-a-azure-container-apps-web-en-contenedor/"&gt;post anterior&lt;/a&gt; os contaba c&amp;oacute;mo he metido la web en un contenedor para pagar bastante menos. Esa parte no se ve, pero esta s&amp;iacute;: la web ten&amp;iacute;a el mismo aspecto desde 2013, con &lt;strong&gt;Bootstrap 3&lt;/strong&gt; y la plantilla &lt;strong&gt;Unify&lt;/strong&gt;, enlaces a redes que ya ni uso y un buen mont&amp;oacute;n de CSS y JavaScript que no hac&amp;iacute;a nada. Ya iba siendo hora.&lt;/p&gt;
&lt;h2&gt;La regla: redise&amp;ntilde;ar sin cambiar la funcionalidad&lt;/h2&gt;
&lt;p&gt;Me puse una condici&amp;oacute;n desde el principio: &lt;strong&gt;el primer paso no pod&amp;iacute;a cambiar nada funcional&lt;/strong&gt;. Mismas rutas, mismos controladores, mismos datos en XML. Solo vistas Razor y estilos. As&amp;iacute;, si algo se romp&amp;iacute;a, sab&amp;iacute;a que era culpa del dise&amp;ntilde;o y no de otra cosa. Las mejoras funcionales (como el filtro de idioma del blog) llegaron despu&amp;eacute;s, cada una en su propio cambio.&lt;/p&gt;
&lt;p&gt;Despu&amp;eacute;s de esa primera pasada, cada p&amp;aacute;gina importante (home, proyectos, biograf&amp;iacute;a y blog) tuvo su &lt;strong&gt;propuesta en HTML est&amp;aacute;tico&lt;/strong&gt; antes de rehacerla: un mockup que se abre en el navegador, con datos reales y, en algunos casos, varias opciones para comparar. Para la cabecera de la home, por ejemplo, hubo tres alternativas lado a lado antes de quedarme con la "editorial". Es mucho m&amp;aacute;s f&amp;aacute;cil decidir viendo algo real que imaginando un wireframe.&lt;/p&gt;
&lt;h2&gt;Tokens en lugar de un framework&lt;/h2&gt;
&lt;p&gt;En vez de cambiar Bootstrap 3 por Bootstrap 5 (o Tailwind), he optado por una &amp;uacute;nica hoja &lt;code&gt;site.scss&lt;/code&gt; propia, construida sobre &lt;strong&gt;variables CSS&lt;/strong&gt; (tokens). Todos los colores salen de ah&amp;iacute;, y el modo oscuro es simplemente redefinir esos tokens con &lt;code&gt;prefers-color-scheme&lt;/code&gt;:&lt;/p&gt;
&lt;pre class="language-scss"&gt;&lt;code&gt;:root {
    --paper: #F4F6F7;
    --ink: #16232E;
    --muted: #556472;
    --accent: #0B5FA5;
    --accent-soft: #DCE8F3;
}

@media (prefers-color-scheme: dark) {
    :root {
        --paper: #0F1920;
        --ink: #E3E9ED;
        --muted: #98A7B2;
        --accent: #6EAEE6;
        --accent-soft: #1D3A52;
        color-scheme: dark;
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Sin clases &lt;code&gt;.dark&lt;/code&gt;, sin JavaScript y sin parpadeos: la web sigue la preferencia del sistema operativo. El logo, un monograma "SG" en SVG, va &lt;em&gt;inline&lt;/em&gt; en la cabecera para que tambi&amp;eacute;n use los tokens y se invierta solo en modo oscuro.&lt;/p&gt;
&lt;p&gt;En tipograf&amp;iacute;a, dos familias: &lt;strong&gt;Schibsted Grotesk&lt;/strong&gt; para la interfaz y los titulares, y &lt;strong&gt;Source Serif 4&lt;/strong&gt; para el cuerpo de los art&amp;iacute;culos, que se leen mucho mejor con una serif y un tama&amp;ntilde;o generoso. Las dos van alojadas en la propia web (m&amp;aacute;s sobre eso en el siguiente post).&lt;/p&gt;
&lt;p&gt;Una peque&amp;ntilde;a an&amp;eacute;cdota: el proyecto compila el SCSS con LibSass, que no entiende &lt;code&gt;clamp()&lt;/code&gt; y falla. El truco es envolverlo para que lo deje pasar tal cual:&lt;/p&gt;
&lt;pre class="language-scss"&gt;&lt;code&gt;.hero h1 { font-size: #{unquote("clamp(36px, 4.6vw, 52px)")}; }&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;P&amp;aacute;gina a p&amp;aacute;gina&lt;/h2&gt;
&lt;p&gt;&lt;img src="https://sergiwebstorage.blob.core.windows.net/blogfiles/Posts/files/p2-home-desktop_639311535255309240.png" alt="La nueva home" width="1280" height="800" /&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Home&lt;/strong&gt;: cabecera editorial con foto, lo que estoy haciendo ahora y el n&amp;uacute;mero de proyectos, seguida de los &amp;uacute;ltimos art&amp;iacute;culos.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Timeline de proyectos&lt;/strong&gt;: mi parte favorita. Una cascada de proyectos desde el a&amp;ntilde;o 2000 al estilo de la pesta&amp;ntilde;a &lt;em&gt;Network&lt;/em&gt; de las DevTools del navegador. Un gui&amp;ntilde;o para quien se dedica a optimizar webs :)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src="https://sergiwebstorage.blob.core.windows.net/blogfiles/Posts/files/p2-timeline_639311536805165579.png" alt="Timeline de proyectos al estilo de la pestaña Network" width="1079" height="564" /&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Proyectos&lt;/strong&gt;: tarjetas con captura, fechas y empresa, y filtros agrupados en "Tipo" y "Empresa" con el n&amp;uacute;mero de proyectos de cada uno. En la ficha, una galer&amp;iacute;a con &lt;code&gt;scroll-snap&lt;/code&gt; nativo, miniaturas y navegaci&amp;oacute;n con teclado.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Biograf&amp;iacute;a&lt;/strong&gt;: antes eran pesta&amp;ntilde;as; ahora es un &amp;uacute;nico scroll con navegaci&amp;oacute;n por anclas, y el detalle de cada puesto plegado en un &lt;code&gt;&amp;lt;details&amp;gt;&lt;/code&gt; para no hacer un tost&amp;oacute;n.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Blog&lt;/strong&gt;: listado por idioma con enlace a la traducci&amp;oacute;n de cada post, tiempo de lectura, art&amp;iacute;culo a una columna y tarjetas de "anterior / siguiente".&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;img src="https://sergiwebstorage.blob.core.windows.net/blogfiles/Posts/files/p2-projects-desktop_639311536809150388.png" alt="Listado de proyectos con filtros agrupados" width="1280" height="800" /&gt;&lt;/p&gt;
&lt;p&gt;Por el camino tambi&amp;eacute;n han desaparecido cosas: los enlaces a Twitter y Facebook, el widget de &amp;uacute;ltimos tweets del footer y el &amp;iacute;ndice de secciones de la home, que duplicaba el men&amp;uacute;. Menos es m&amp;aacute;s.&lt;/p&gt;
&lt;h2&gt;Revisar en todos los tama&amp;ntilde;os (y colores)&lt;/h2&gt;
&lt;p&gt;Sin una bater&amp;iacute;a de tests visuales, la verificaci&amp;oacute;n ha sido manual pero sistem&amp;aacute;tica: cada cambio revisado en escritorio y a &lt;strong&gt;375 px&lt;/strong&gt;, en claro y en oscuro. Aqu&amp;iacute; la IA vuelve a ser &amp;uacute;til: con &lt;a title="Claude Code" href="https://claude.com/claude-code" target="_blank" rel="noopener"&gt;Claude Code&lt;/a&gt; controlando un navegador, puedo pedirle que abra cada p&amp;aacute;gina en las cuatro combinaciones, haga capturas y me se&amp;ntilde;ale desbordamientos o contrastes raros. Es como tener a alguien haciendo el QA aburrido mientras t&amp;uacute; decides si el gris es demasiado gris.&lt;/p&gt;
&lt;p&gt;&lt;img src="https://sergiwebstorage.blob.core.windows.net/blogfiles/Posts/files/p2-home-mobile-dark_639311536809371362.png" alt="La home en móvil y modo oscuro" width="375" height="780" /&gt;&lt;/p&gt;
&lt;p&gt;Eso s&amp;iacute;, el criterio est&amp;eacute;tico sigue siendo humano. La IA genera propuestas r&amp;aacute;pido, pero muchas eran "correctas" y gen&amp;eacute;ricas; las mejores ideas (como el timeline tipo DevTools) salieron de iterar sobre ellas con una opini&amp;oacute;n clara de lo que quer&amp;iacute;a.&lt;/p&gt;
&lt;h2&gt;Y ahora, a por el rendimiento&lt;/h2&gt;
&lt;p&gt;Con el nuevo dise&amp;ntilde;o, buena parte del CSS y el JavaScript de 2013 se qued&amp;oacute; sin uso... pero segu&amp;iacute;a carg&amp;aacute;ndose en cada p&amp;aacute;gina. En el siguiente y &amp;uacute;ltimo post de la serie cuento c&amp;oacute;mo lo he limpiado, c&amp;oacute;mo he quitado jQuery por completo y c&amp;oacute;mo he reducido el arranque en fr&amp;iacute;o del contenedor.&lt;/p&gt;</description>
  <author>Sergi Gisbert</author>
  <category>claude code</category>
  <category>ux</category>
  <category>css</category>
  <category>frontend</category>
  <category>diseño</category>
  <category>personal</category>
  <guid isPermaLink="false">https://www.sergigisbert.com/blog/rediseno-de-la-web-sistema-visual-propio/</guid>
  <pubDate>Mon, 30 Nov 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>De IIS a Azure Container Apps: la web, en un contenedor y bastante más barata</title>
  <link>https://www.sergigisbert.com/blog/de-iis-a-azure-container-apps-web-en-contenedor/</link>
  <description>&lt;p&gt;All&amp;aacute; por diciembre de 2020 os contaba en &lt;a title="Website actualizado a ASP.NET MVC Core" href="/blog/website-actualizado-a-aspnet-mvc-core/"&gt;"Website actualizado a ASP.NET MVC Core"&lt;/a&gt; que hab&amp;iacute;a migrado la web a .Net Core, y terminaba diciendo que lo siguiente ser&amp;iacute;a pasar a .Net 5 y a Azure Tables... Pues bien, ni una cosa ni la otra :) Lo que s&amp;iacute; ha llegado, cinco a&amp;ntilde;os despu&amp;eacute;s, es una actualizaci&amp;oacute;n bastante m&amp;aacute;s interesante para el bolsillo.&lt;/p&gt;
&lt;p&gt;Esta es la primera de una serie de tres entradas en las que repaso la puesta al d&amp;iacute;a de la web:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;De IIS a Azure Container Apps&lt;/strong&gt; (este post): infraestructura y ahorro de costes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Redise&amp;ntilde;o visual&lt;/strong&gt;: adi&amp;oacute;s a Bootstrap 3 y a la plantilla de 2013.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Optimizaciones de rendimiento&lt;/strong&gt;: menos JavaScript y un arranque en fr&amp;iacute;o mucho m&amp;aacute;s r&amp;aacute;pido.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;El problema: pagar por tener la luz encendida&lt;/h2&gt;
&lt;p&gt;La web viv&amp;iacute;a en un &lt;strong&gt;Azure App Service sobre Windows&lt;/strong&gt;, es decir, IIS con su &lt;code&gt;web.config&lt;/code&gt;, siempre encendido y con un plan dimensionado para "por si acaso". Para una web personal con poco tr&amp;aacute;fico, eso eran &lt;strong&gt;63,28 &amp;euro; al mes&lt;/strong&gt; sin IVA (76,57 &amp;euro; con IVA, factura de marzo de 2026) por tener una m&amp;aacute;quina esperando a que alguien entrase. No tiene mucho sentido.&lt;/p&gt;
&lt;p&gt;El plan a largo plazo es otro (ya llegar&amp;aacute;), pero quer&amp;iacute;a un &lt;em&gt;quick win&lt;/em&gt;: reducir la factura sin reescribir la aplicaci&amp;oacute;n. Y ah&amp;iacute; encaja muy bien &lt;a title="Azure Container Apps" href="https://learn.microsoft.com/azure/container-apps/overview" target="_blank" rel="noopener"&gt;Azure Container Apps&lt;/a&gt;: empaquetas la app en una imagen Docker y Azure la escala seg&amp;uacute;n el tr&amp;aacute;fico, &lt;strong&gt;incluso a cero r&amp;eacute;plicas&lt;/strong&gt; cuando no hay nadie. Solo pagas por el tiempo en el que el contenedor est&amp;aacute; trabajando.&lt;/p&gt;
&lt;h2&gt;Meter la web en un contenedor&lt;/h2&gt;
&lt;p&gt;La aplicaci&amp;oacute;n sigue en ASP.NET Core 3.1 (s&amp;iacute;, ya s&amp;eacute; que est&amp;aacute; fuera de soporte, todo llegar&amp;aacute;), con dos librer&amp;iacute;as a su lado, &lt;code&gt;Model.Net&lt;/code&gt; y &lt;code&gt;Shared&lt;/code&gt;. Por eso el &lt;code&gt;Dockerfile&lt;/code&gt; se construye desde la ra&amp;iacute;z del repositorio y no desde &lt;code&gt;src/&lt;/code&gt;. Es un multi-stage de lo m&amp;aacute;s cl&amp;aacute;sico: copiar primero los &lt;code&gt;.csproj&lt;/code&gt; para aprovechar la cach&amp;eacute; de capas en el &lt;code&gt;restore&lt;/code&gt;, publicar en Release y quedarse solo con el runtime:&lt;/p&gt;
&lt;pre class="language-docker"&gt;&lt;code&gt;# ── Stage 1: Build ──
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /repo
COPY Miniblog.Core.sln ./
COPY src/Miniblog.Core.csproj ./src/
COPY Model.Net/Model.csproj ./Model.Net/
COPY Shared/Shared.csproj ./Shared/
RUN dotnet restore src/Miniblog.Core.csproj

COPY src/ ./src/
COPY Model.Net/ ./Model.Net/
COPY Shared/ ./Shared/
RUN dotnet publish src/Miniblog.Core.csproj -c Release -o /app/publish

# ── Stage 2: Runtime ──
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS runtime
WORKDIR /app
COPY --from=build /app/publish .
EXPOSE 80
ENTRYPOINT ["dotnet", "Miniblog.Core.dll"]&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Las piedras del camino: de Windows a Linux&lt;/h2&gt;
&lt;p&gt;Lo de "sin tocar el c&amp;oacute;digo" dur&amp;oacute; poco. La primera sorpresa fue que &lt;code&gt;Model.Net&lt;/code&gt; segu&amp;iacute;a siendo una librer&amp;iacute;a de &lt;strong&gt;.NET Framework 4.8&lt;/strong&gt;, heredada de la versi&amp;oacute;n de 2013, y eso obliga a im&amp;aacute;genes Windows. As&amp;iacute; que toc&amp;oacute; migrarla a &lt;code&gt;netstandard2.0&lt;/code&gt; y, de paso, sustituir el acceso a rutas v&amp;iacute;a &lt;code&gt;AppDomain&lt;/code&gt;, que en .NET Core ya no tiene sentido:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;// Antes (.NET Framework)
var rootPath = (string)AppDomain.CurrentDomain.GetData(AppDomainConstants.ContentRootPath);

// Ahora (netstandard2.0)
_contentRootPath = hostingEnvironment?.ContentRootPath ?? AppContext.BaseDirectory;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Y luego, los cl&amp;aacute;sicos de quien ha vivido siempre en Windows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Separadores de ruta&lt;/strong&gt;: &lt;code&gt;"xml-data\\Projects.xml"&lt;/code&gt; funciona en Windows, pero en Linux no existe ese fichero. Cambiado a &lt;code&gt;/&lt;/code&gt;, que funciona en los dos.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;May&amp;uacute;sculas y min&amp;uacute;sculas&lt;/strong&gt;: en Linux, &lt;code&gt;Foto.PNG&lt;/code&gt; y &lt;code&gt;foto.png&lt;/code&gt; son dos ficheros distintos. Algunas im&amp;aacute;genes de proyectos dejaron de verse hasta que aline&amp;eacute; los nombres del XML con los ficheros reales.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Slugs inexistentes&lt;/strong&gt;: una URL de proyecto que no exist&amp;iacute;a lanzaba una excepci&amp;oacute;n sin controlar. Ahora redirige a la home.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;CI/CD con Azure DevOps&lt;/h2&gt;
&lt;p&gt;Ahora cada push a &lt;code&gt;main&lt;/code&gt; lanza un pipeline de Azure DevOps con tres etapas: construir y subir la imagen a Azure Container Registry, actualizar el Container App con la nueva etiqueta, y verificar. El despliegue, en esencia, es una sola l&amp;iacute;nea de Azure CLI:&lt;/p&gt;
&lt;pre class="language-none"&gt;&lt;code&gt;az containerapp update \
  --name $(containerAppName) \
  --resource-group $(resourceGroup) \
  --image $(acrRegistry)/$(dockerImageName):linux-$(Build.SourceVersion)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;La etapa de verificaci&amp;oacute;n ejecuta un peque&amp;ntilde;o script, &lt;code&gt;check-routes.ps1&lt;/code&gt;, que comprueba que las rutas principales (&lt;code&gt;/es&lt;/code&gt;, &lt;code&gt;/en&lt;/code&gt;, &lt;code&gt;/blog&lt;/code&gt;, proyectos, biograf&amp;iacute;a...) devuelven un 200 sin redirecciones. Si algo falla, el pipeline se pone en rojo antes de que me entere por otro lado. Delante de todo est&amp;aacute; &lt;strong&gt;Cloudflare&lt;/strong&gt;, que ya gestionaba el DNS y el certificado, y que en el tercer post tendr&amp;aacute; bastante m&amp;aacute;s protagonismo.&lt;/p&gt;
&lt;h2&gt;Con ayuda de la IA&lt;/h2&gt;
&lt;p&gt;No os voy a enga&amp;ntilde;ar: buena parte de este trabajo lo he hecho mano a mano con &lt;a title="Claude Code" href="https://claude.com/claude-code" target="_blank" rel="noopener"&gt;Claude Code&lt;/a&gt;, el asistente de programaci&amp;oacute;n de Anthropic. La migraci&amp;oacute;n se planific&amp;oacute; con &amp;eacute;l como un documento con tareas verificables (Dockerfile, pipeline, variables de entorno, dominio...), que se iban ejecutando y marcando una a una, y cada problema de Linux que aparec&amp;iacute;a en el contenedor se depuraba en el momento.&lt;/p&gt;
&lt;p&gt;M&amp;aacute;s adelante, con la web ya en el contenedor, di un paso m&amp;aacute;s: &lt;strong&gt;encapsular procesos repetitivos&lt;/strong&gt; en el propio repositorio, que es lo que m&amp;aacute;s valor me ha aportado:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Una &lt;em&gt;skill&lt;/em&gt; &lt;code&gt;/smoke-test&lt;/code&gt; que levanta el contenedor en local con &lt;code&gt;run-docker.ps1&lt;/code&gt; y pasa el mismo &lt;code&gt;check-routes.ps1&lt;/code&gt; del pipeline.&lt;/li&gt;
&lt;li&gt;Un &lt;em&gt;hook&lt;/em&gt; que lanza &lt;code&gt;dotnet build&lt;/code&gt; cada vez que se edita un &lt;code&gt;.cs&lt;/code&gt; y devuelve los errores al momento.&lt;/li&gt;
&lt;li&gt;Otro &lt;em&gt;hook&lt;/em&gt; que impide editar por error &lt;code&gt;bin/&lt;/code&gt;, &lt;code&gt;obj/&lt;/code&gt; o copias de trabajo duplicadas.&lt;/li&gt;
&lt;li&gt;Un subagente de solo lectura, &lt;code&gt;upgrade-auditor&lt;/code&gt;, que revisa qu&amp;eacute; bloquea cada una de las pr&amp;oacute;ximas fases de la migraci&amp;oacute;n.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;La IA propone y ejecuta, pero las decisiones siguen siendo m&amp;iacute;as. Como siempre, conviene tratarla como a un compa&amp;ntilde;ero junior muy r&amp;aacute;pido: le revisas todo.&lt;/p&gt;
&lt;h2&gt;El resultado&lt;/h2&gt;
&lt;p&gt;La web funciona igual que antes, pero ahora corre en un contenedor Linux que puede apagarse cuando nadie la visita. Y la factura lo nota: la de octubre de 2026, con el contenedor ya en marcha, se queda en &lt;strong&gt;20,82 &amp;euro;&lt;/strong&gt; (25,19 &amp;euro; con IVA), frente a los 63,28 &amp;euro; (76,57 &amp;euro; con IVA) de marzo. Es decir, unos &lt;strong&gt;510 &amp;euro; menos al a&amp;ntilde;o&lt;/strong&gt; sin IVA, m&amp;aacute;s de 600 &amp;euro; con IVA. El desglose: 16,02 &amp;euro; del propio Container App (0,25 vCPU y 0,5 GB), 4,54 &amp;euro; del Container Registry y 0,26 &amp;euro; de almacenamiento. Los App Service antiguos siguen ah&amp;iacute;, pero en el plan gratuito F1.&lt;/p&gt;
&lt;p&gt;Eso s&amp;iacute;, m&amp;aacute;s de lo que hab&amp;iacute;a estimado al planificar (entre 5 y 13 &amp;euro;), y al mirar las m&amp;eacute;tricas entend&amp;iacute; por qu&amp;eacute;: en octubre la r&amp;eacute;plica estuvo encendida &lt;strong&gt;743 de las 744 horas&lt;/strong&gt; del mes. Con unas 99.000 peticiones (una cada ~27 segundos, entre visitas, buscadores y bots) y un &lt;em&gt;cooldown&lt;/em&gt; de 5 minutos, el contenedor nunca llega a apagarse. El &lt;em&gt;scale to zero&lt;/em&gt; funciona, pero solo si hay silencio. Ah&amp;iacute; entra la cach&amp;eacute; de Cloudflare del tercer post: cuantas menos peticiones lleguen al origen, m&amp;aacute;s horas a cero.&lt;/p&gt;
&lt;p&gt;&amp;iquest;Y el precio a pagar? El &lt;strong&gt;arranque en fr&amp;iacute;o&lt;/strong&gt;: si la r&amp;eacute;plica est&amp;aacute; a cero, la primera visita tiene que esperar a que el contenedor arranque. C&amp;oacute;mo he recortado esa espera lo cuento en el tercer post de la serie, pero antes toca hablar de algo m&amp;aacute;s visible: el redise&amp;ntilde;o.&lt;/p&gt;</description>
  <author>Sergi Gisbert</author>
  <category>claude code</category>
  <category>devops</category>
  <category>azure container apps</category>
  <category>docker</category>
  <category>azure</category>
  <category>personal</category>
  <guid isPermaLink="false">https://www.sergigisbert.com/blog/de-iis-a-azure-container-apps-web-en-contenedor/</guid>
  <pubDate>Wed, 25 Nov 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>From IIS to Azure Container Apps: my website, containerised and a lot cheaper</title>
  <link>https://www.sergigisbert.com/blog/from-iis-to-azure-container-apps-containerised-website/</link>
  <description>&lt;p&gt;Back in December 2020 I wrote (in Spanish) about &lt;a title="Website actualizado a ASP.NET MVC Core" href="/blog/website-actualizado-a-aspnet-mvc-core/"&gt;moving this website to ASP.NET Core&lt;/a&gt;, and I finished by saying the next step would be .NET 5 and Azure Tables... Well, neither happened :) What did happen, five years later, is an update that is much kinder to my wallet.&lt;/p&gt;
&lt;p&gt;This is the first of three posts about bringing the site up to date:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;From IIS to Azure Container Apps&lt;/strong&gt; (this post): infrastructure and cost savings.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Visual redesign&lt;/strong&gt;: goodbye Bootstrap 3 and the 2013 template.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Performance optimisations&lt;/strong&gt;: less JavaScript and a much faster cold start.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;The problem: paying to keep the lights on&lt;/h2&gt;
&lt;p&gt;The site lived on an &lt;strong&gt;Azure App Service on Windows&lt;/strong&gt;: IIS with its &lt;code&gt;web.config&lt;/code&gt;, always on, on a plan sized "just in case". For a low-traffic personal site, that meant &lt;strong&gt;&amp;euro;63.28 a month&lt;/strong&gt; before VAT (&amp;euro;76.57 with it, March 2026 bill) for a machine waiting for someone to show up. Not much sense in that.&lt;/p&gt;
&lt;p&gt;The long-term plan is something else (more on that some day), but I wanted a quick win: cut the bill without rewriting the app. &lt;a title="Azure Container Apps" href="https://learn.microsoft.com/azure/container-apps/overview" target="_blank" rel="noopener"&gt;Azure Container Apps&lt;/a&gt; fits that nicely: you package the app as a Docker image and Azure scales it with traffic, &lt;strong&gt;down to zero replicas&lt;/strong&gt; when nobody is around. You only pay while the container is actually working.&lt;/p&gt;
&lt;h2&gt;Putting the site in a container&lt;/h2&gt;
&lt;p&gt;The app is still ASP.NET Core 3.1 (yes, I know it is out of support, one thing at a time), with two libraries next to it, &lt;code&gt;Model.Net&lt;/code&gt; and &lt;code&gt;Shared&lt;/code&gt;. That is why the &lt;code&gt;Dockerfile&lt;/code&gt; builds from the repository root instead of &lt;code&gt;src/&lt;/code&gt;. It is a textbook multi-stage build: copy the &lt;code&gt;.csproj&lt;/code&gt; files first so the &lt;code&gt;restore&lt;/code&gt; layer is cached, publish in Release, and keep only the runtime:&lt;/p&gt;
&lt;pre class="language-docker"&gt;&lt;code&gt;# ── Stage 1: Build ──
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /repo
COPY Miniblog.Core.sln ./
COPY src/Miniblog.Core.csproj ./src/
COPY Model.Net/Model.csproj ./Model.Net/
COPY Shared/Shared.csproj ./Shared/
RUN dotnet restore src/Miniblog.Core.csproj

COPY src/ ./src/
COPY Model.Net/ ./Model.Net/
COPY Shared/ ./Shared/
RUN dotnet publish src/Miniblog.Core.csproj -c Release -o /app/publish

# ── Stage 2: Runtime ──
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS runtime
WORKDIR /app
COPY --from=build /app/publish .
EXPOSE 80
ENTRYPOINT ["dotnet", "Miniblog.Core.dll"]&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Bumps in the road: from Windows to Linux&lt;/h2&gt;
&lt;p&gt;"Without touching the code" did not last long. First surprise: &lt;code&gt;Model.Net&lt;/code&gt; was still a &lt;strong&gt;.NET Framework 4.8&lt;/strong&gt; library inherited from the 2013 version, which means Windows images. So I migrated it to &lt;code&gt;netstandard2.0&lt;/code&gt; and, while at it, replaced the &lt;code&gt;AppDomain&lt;/code&gt;-based path lookup, which makes no sense in .NET Core:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;// Before (.NET Framework)
var rootPath = (string)AppDomain.CurrentDomain.GetData(AppDomainConstants.ContentRootPath);

// Now (netstandard2.0)
_contentRootPath = hostingEnvironment?.ContentRootPath ?? AppContext.BaseDirectory;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And then the classics for anyone who has always lived on Windows:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Path separators&lt;/strong&gt;: &lt;code&gt;"xml-data\\Projects.xml"&lt;/code&gt; works on Windows, but on Linux there is no such file. Switched to &lt;code&gt;/&lt;/code&gt;, which works on both.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Case sensitivity&lt;/strong&gt;: on Linux, &lt;code&gt;Photo.PNG&lt;/code&gt; and &lt;code&gt;photo.png&lt;/code&gt; are two different files. Some project images vanished until I matched the names in the XML to the real files.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Unknown slugs&lt;/strong&gt;: a project URL that did not exist threw an unhandled exception. It now redirects to the home page.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;CI/CD with Azure DevOps&lt;/h2&gt;
&lt;p&gt;Now every push to &lt;code&gt;main&lt;/code&gt; runs an Azure DevOps pipeline with three stages: build the image and push it to Azure Container Registry, update the Container App with the new tag, and verify. The deployment itself is basically a single Azure CLI command:&lt;/p&gt;
&lt;pre class="language-none"&gt;&lt;code&gt;az containerapp update \
  --name $(containerAppName) \
  --resource-group $(resourceGroup) \
  --image $(acrRegistry)/$(dockerImageName):linux-$(Build.SourceVersion)&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The verify stage runs a small script, &lt;code&gt;check-routes.ps1&lt;/code&gt;, which checks that the main routes (&lt;code&gt;/es&lt;/code&gt;, &lt;code&gt;/en&lt;/code&gt;, &lt;code&gt;/blog&lt;/code&gt;, projects, biography...) return a 200 with no redirects. If anything breaks, the pipeline goes red before I find out some other way. In front of everything sits &lt;strong&gt;Cloudflare&lt;/strong&gt;, which already handled DNS and TLS, and which plays a much bigger part in the third post.&lt;/p&gt;
&lt;h2&gt;With a little help from AI&lt;/h2&gt;
&lt;p&gt;I won't pretend otherwise: a good part of this work was done side by side with &lt;a title="Claude Code" href="https://claude.com/claude-code" target="_blank" rel="noopener"&gt;Claude Code&lt;/a&gt;, Anthropic's coding assistant. The migration was planned with it as a document of verifiable tasks (Dockerfile, pipeline, environment variables, domain...), executed and ticked off one by one, and every Linux issue that showed up in the container was debugged on the spot.&lt;/p&gt;
&lt;p&gt;Later on, with the site already in the container, I went a step further: &lt;strong&gt;capturing repetitive processes&lt;/strong&gt; inside the repository itself, which is what I value most:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;A &lt;code&gt;/smoke-test&lt;/code&gt; &lt;em&gt;skill&lt;/em&gt; that starts the container locally with &lt;code&gt;run-docker.ps1&lt;/code&gt; and runs the same &lt;code&gt;check-routes.ps1&lt;/code&gt; as the pipeline.&lt;/li&gt;
&lt;li&gt;A &lt;em&gt;hook&lt;/em&gt; that runs &lt;code&gt;dotnet build&lt;/code&gt; every time a &lt;code&gt;.cs&lt;/code&gt; file is edited and reports errors straight away.&lt;/li&gt;
&lt;li&gt;Another &lt;em&gt;hook&lt;/em&gt; that blocks accidental edits in &lt;code&gt;bin/&lt;/code&gt;, &lt;code&gt;obj/&lt;/code&gt; or duplicate working copies.&lt;/li&gt;
&lt;li&gt;A read-only subagent, &lt;code&gt;upgrade-auditor&lt;/code&gt;, that reviews what blocks each of the upcoming migration phases.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The AI proposes and executes, but the decisions are still mine. As always, treat it like a very fast junior colleague: you review everything.&lt;/p&gt;
&lt;h2&gt;The result&lt;/h2&gt;
&lt;p&gt;The site works exactly as before, but it now runs in a Linux container that can shut down when nobody is visiting. And the bill shows it: October 2026, with the container already running, came to &lt;strong&gt;&amp;euro;20.82&lt;/strong&gt; (&amp;euro;25.19 including VAT), compared with &amp;euro;63.28 (&amp;euro;76.57 including VAT) in March. That is roughly &lt;strong&gt;&amp;euro;510 less per year&lt;/strong&gt; before VAT, over &amp;euro;600 with it. The breakdown: &amp;euro;16.02 for the Container App itself (0.25 vCPU and 0.5 GB), &amp;euro;4.54 for the Container Registry and &amp;euro;0.26 for storage. The old App Services are still there, but on the free F1 plan.&lt;/p&gt;
&lt;p&gt;Still, that is more than I estimated when planning (between &amp;euro;5 and &amp;euro;13), and the metrics explained why: in October the replica was up for &lt;strong&gt;743 of the month's 744 hours&lt;/strong&gt;. With around 99,000 requests (one every ~27 seconds, between visitors, search engines and bots) and a 5-minute cooldown, the container never gets the chance to shut down. Scale to zero works, but only when things go quiet. That is where the Cloudflare cache from the third post comes in: the fewer requests reach the origin, the more hours at zero.&lt;/p&gt;
&lt;p&gt;The price to pay? The &lt;strong&gt;cold start&lt;/strong&gt;: when the replica is at zero, the first visitor waits for the container to boot. How I made that wait a lot shorter is in the third post, but first, something more visible: the redesign.&lt;/p&gt;</description>
  <author>Sergi Gisbert</author>
  <category>claude code</category>
  <category>devops</category>
  <category>azure container apps</category>
  <category>docker</category>
  <category>azure</category>
  <category>personal</category>
  <category>english</category>
  <guid isPermaLink="false">https://www.sergigisbert.com/blog/from-iis-to-azure-container-apps-containerised-website/</guid>
  <pubDate>Wed, 25 Nov 2026 00:00:00 GMT</pubDate>
</item>
<item>
  <title>How to make an external API request in Blazor using Refit</title>
  <link>https://www.sergigisbert.com/blog/how-to-make-an-external-api-request-in-blazor-using-refit/</link>
  <description>&lt;p&gt;&lt;strong&gt;Blazor&lt;/strong&gt; is the new development framework to develop SPA websites from Microsoft, and it is getting quite some attention lately. In this article, I'll do a simple demostration on how to make a request to an external API and displaying some data, using &lt;strong&gt;Refit&lt;/strong&gt; library in an easy way.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Blazor&lt;/strong&gt;&amp;nbsp;allows to create website applications running &lt;strong&gt;C#&lt;/strong&gt;&amp;nbsp;on the client side, so effectively, most of the developers who consider ourselves mostly Backend devs, can now make the transition to become&amp;nbsp;&lt;strong&gt;Full-Stack&lt;/strong&gt;&amp;nbsp;without the need of learning another client side framework like Angular or React. Also, there are already several UI control libraries for Blazor, some even free like&amp;nbsp;&lt;a href="https://blazor.radzen.com/" target="_blank" rel="noopener"&gt;Radzen&lt;/a&gt;. My last real-world application I developed myself using Blazor can be browsed at&amp;nbsp;&lt;a href="https://www.saboraemocion.com/" target="_blank" rel="noopener"&gt;https://www.saboraemocion.com/&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Making an introduction to Blazor is not the goal of this post, as there is already quite some good documentation on the topic to get you started pretty fast, and I recommend to start with the official docs and tutorials, at&amp;nbsp;&lt;a href="https://dotnet.microsoft.com/apps/aspnet/web-apps/blazor" target="_blank" rel="noopener"&gt;https://dotnet.microsoft.com/apps/aspnet/web-apps/blazor&lt;/a&gt;.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;What actually I'll be doing is to use a Blazor sample project to introduce you to &lt;a href="https://github.com/reactiveui/refit" target="_blank" rel="noopener"&gt;Refit&lt;/a&gt;, which is, quoting themselves "The automatic type-safe REST library for .NET Core, Xamarin and .NET", meaning it will automatically create an API client for us, starting from an Interface definition.&amp;nbsp;&lt;strong&gt;Refit&lt;/strong&gt;&amp;nbsp;will take care of the low-level details: HTTP requests, authetication, headers, serialization, type conversion, etc.&amp;nbsp;I will use Refit to create a small currency exchange conversion tool, with the data coming from the free API at&amp;nbsp;&lt;a href="https://api.exchangeratesapi.io/" target="_blank" rel="noopener"&gt;https://api.exchangeratesapi.io/&lt;/a&gt;&amp;nbsp;(you can see the service details at&amp;nbsp;&lt;a href="https://exchangeratesapi.io/" target="_blank" rel="noopener"&gt;https://exchangeratesapi.io/&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;The source code can be found at&amp;nbsp;&lt;a href="https://github.com/sgisbert/blazor-currencyexchange" target="_blank" rel="noopener"&gt;https://github.com/sgisbert/blazor-currencyexchange&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Initial configuration&lt;/h2&gt;
&lt;p&gt;For this simple example, we are creating a SPA application with &lt;strong&gt;Blazor Server&lt;/strong&gt;&amp;nbsp;and .Net 5. It can also be done using a model based on client and&amp;nbsp;&lt;strong&gt;Blazor WebAssembly&lt;/strong&gt;. Check the differences between both hosting models here:&amp;nbsp;&lt;a href="https://docs.microsoft.com/aspnet/core/blazor/hosting-models" target="_blank" rel="noopener"&gt;https://docs.microsoft.com/aspnet/core/blazor/hosting-models&lt;/a&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;To create the new application, we can make use of the Visual Studio wizard, or simply, as per the &lt;a href="https://dotnet.microsoft.com/learn/aspnet/blazor-tutorial/intro" target="_blank" rel="noopener"&gt;Blazor tutorial&lt;/a&gt;, run the following command from the console:&lt;/p&gt;
&lt;pre class="language-markup"&gt;&lt;code&gt;dotnet new blazorserver -o BlazorApp&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;And to check that everything is working, we change folder to the "BlazorApp" created, and run:&lt;/p&gt;
&lt;pre class="language-markup"&gt;&lt;code&gt;dotnet watch run&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;this will compile the application, run it, and will keep watching the source code, to build and restart again every time a code change is made. To stop it, we just need to hit &lt;strong&gt;Ctrl&lt;/strong&gt;+&lt;strong&gt;C&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;When it completes building, it will display that the app is listening to &lt;strong&gt;http://localhost:5001&lt;/strong&gt;&amp;nbsp;and our default browser will pop up on that address, showing the scaffolded app we just created:&lt;/p&gt;
&lt;p style="text-align: center;"&gt;&lt;img src="https://sergiwebstorage.blob.core.windows.net/blogfiles/Posts\files\Image1_637495089046259032.png" alt="Image1.png" width="929" height="564" /&gt;&lt;/p&gt;
&lt;p style="text-align: center;"&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Adding the business logic&lt;/h2&gt;
&lt;p&gt;The goal on this example will be listing the currency exchange values available for the current date. For that, we need to call the endpoint at&amp;nbsp;&lt;strong&gt;https://api.exchangeratesapi.io/latest&lt;/strong&gt;, that will return a JSON object like this:&amp;nbsp;&lt;/p&gt;
&lt;pre class="language-javascript"&gt;&lt;code&gt;{"rates":{"CAD":1.5307,"HKD":9.4121,"ISK":155.6,"PHP":58.846,"DKK":7.4368,"HUF":358.5,"CZK":25.849,"AUD":1.5445,"RON":4.8758,"SEK":10.033,"IDR":17094.81,"INR":88.0145,"BRL":6.5633,"RUB":89.6089,"HRK":7.578,"JPY":127.81,"THB":36.386,"CHF":1.0851,"SGD":1.6059,"PLN":4.483,"BGN":1.9558,"TRY":8.447,"CNY":7.8318,"NOK":10.2095,"NZD":1.6642,"ZAR":17.7391,"USD":1.2139,"MXN":24.7094,"ILS":3.97,"GBP":0.86508,"KRW":1339.59,"MYR":4.9048},"base":"EUR","date":"2021-02-19"}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Where we have all the different exchange prices against Euro for each currency, for the last published date.&lt;/p&gt;
&lt;p&gt;The first thing I usually do is to create a new project on the solution to keep the business logic. This is not strictly necessary for this sample, but helps keeping up with best practices ;). To do so, I created a new .Net 5 library in the solution, called "Domain". In terms of "Domain Driven Development" (DDD) methodology, this will be our domain layer:&lt;/p&gt;
&lt;p style="text-align: center;"&gt;&lt;img src="https://sergiwebstorage.blob.core.windows.net/blogfiles/Posts\files\Image3_637495089051827731.png" alt="Image3.png" width="343" height="80" /&gt;&lt;/p&gt;
&lt;p&gt;Again, full source code is on &lt;a href="https://github.com/sgisbert/blazor-currencyexchange/tree/4c7a62f6b07ccdcf406cee98fbe0afd50e87ed33" target="_blank" rel="noopener"&gt;GitHub&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Once we got the new project, we will start creating the data model to work with. To generate the model in C#, we can use a tool like &lt;a href="https://app.quicktype.io/" target="_blank" rel="noopener"&gt;https://app.quicktype.io/&lt;/a&gt;, which will generate a complete C# class&amp;nbsp; from the previous JSON data, optionally including helper methods to serialize and deserialize the data:&lt;/p&gt;
&lt;p style="text-align: center;"&gt;&lt;img src="https://sergiwebstorage.blob.core.windows.net/blogfiles/Posts\files\image2_637495089052883030.png" alt="image2.png" width="1116" height="792" /&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;We will add the generated code to class&amp;nbsp;&lt;strong&gt;Model/Rates.cs&amp;nbsp;&lt;/strong&gt;(we'll need to add a reference to the Nuget package&amp;nbsp;&lt;strong&gt;Newtonsoft.Json&lt;/strong&gt;):&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;namespace Domain.Model
{
    using System;
    using System.Collections.Generic;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    public partial class Rates
    {
        [JsonProperty("rates")]
        public Dictionary&amp;lt;string, double&amp;gt; RateList { get; set; }

        [JsonProperty("base")]
        public string Base { get; set; }

        [JsonProperty("date")]
        public DateTimeOffset Date { get; set; }
    }

    public partial class Rates
    {
        public static Rates FromJson(string json) =&amp;gt; JsonConvert.DeserializeObject&amp;lt;Rates&amp;gt;(json, Converter.Settings);
    }

    public static class Serialize
    {
        public static string ToJson(this Rates self) =&amp;gt; JsonConvert.SerializeObject(self, Converter.Settings);
    }

    internal static class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters = {
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
        };
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Next, we are using &lt;strong&gt;Refit&lt;/strong&gt;&amp;nbsp;to define the service that will make use of the API. For that, first thing is to include the nuget package&amp;nbsp;&lt;strong&gt;Refit.HttpClientFactory&lt;/strong&gt;&amp;nbsp;in the project (&lt;span style="color: #808080;"&gt;&lt;em&gt;&lt;strong&gt;Note&lt;/strong&gt;: at the moment of writing this post, we are using Refit version 5.1.2. If you install version 6.x or higher it might not work straight away, because the default serializer engine has been changed from Newtonsoft.Json to System.Text.Json. I recommend to keep using 5.1.2 to follow the example without any issues, but have a look at the latest for new projects&lt;/em&gt;&lt;/span&gt;)&lt;/p&gt;
&lt;p&gt;We add the following Interface to the Domain project&amp;nbsp;&lt;strong&gt;Services/ICurrencyApi.cs&lt;/strong&gt;:&amp;nbsp;&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;using Domain.Model;
using Refit;
using System.Threading.Tasks;

namespace Domain.Services
{
    [Headers("Content-Type: application/json")]
    public interface ICurrencyApi
    {
        [Get("/latest")]
        Task&amp;lt;ApiResponse&amp;lt;Rates&amp;gt;&amp;gt; GetLatest();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Where we are defining the request to the "latest" endpoint from the API, which will return an object of type "&lt;strong&gt;ApiResponse&amp;lt;Rates&amp;gt;&lt;/strong&gt;", where &lt;em&gt;ApiResponse&lt;/em&gt;&amp;nbsp;will have the information of the request (http response code, errors, etc.) and the content of the response, which is our business model,&amp;nbsp;&lt;em&gt;Rates&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Next, we are adding the service that will make use of the Refit service,&amp;nbsp;&lt;strong&gt;Services/ICurrencyService.cs&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;using Domain.Model;
using Refit;
using System.Threading.Tasks;

namespace Domain.Services
{
    public interface ICurrencyService
    {
        Task&amp;lt;ApiResponse&amp;lt;Rates&amp;gt;&amp;gt; GetLatest();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;and its implementation,&amp;nbsp;&lt;strong&gt;Services/CurrencyService.cs&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;using Domain.Model;
using Refit;
using System.Threading.Tasks;

namespace Domain.Services
{
    public class CurrencyService : ICurrencyService
    {
        private readonly ICurrencyApi _api;

        public CurrencyService(ICurrencyApi api)
        {
            _api = api;
        }

        public async Task&amp;lt;ApiResponse&amp;lt;Rates&amp;gt;&amp;gt; GetLatest()
        {
            return await _api.GetLatest();
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Finally, we will add a class to our library in charge of initializing the services we just created, so that netcore dependency injection is able to instantiate them correctly,&amp;nbsp;&lt;strong&gt;DomainStartup.cs&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;using Domain.Services;
using Microsoft.Extensions.DependencyInjection;
using Refit;
using System;

namespace Domain
{
    public static class DomainStartup
    {
        public static void InitDomain(this IServiceCollection services)
        {
            services.AddScoped&amp;lt;ICurrencyService, CurrencyService&amp;gt;();

            services.AddRefitClient&amp;lt;ICurrencyApi&amp;gt;()
                    .ConfigureHttpClient(c =&amp;gt; c.BaseAddress = new Uri("https://api.exchangeratesapi.io/"))
                    .SetHandlerLifetime(TimeSpan.FromMinutes(2));
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;In this case, we initialize our &lt;strong&gt;CurrencyService&lt;/strong&gt;, and make use of method&amp;nbsp;&lt;strong&gt;AddRefitClient&lt;/strong&gt;&amp;nbsp;to tell Refit the initialization values for the API, and the base URL of the service.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Using the service in the Blazor application&lt;/h2&gt;
&lt;p&gt;Until now, we have not modified anything on the Blazor application we created at the beginning. At this point, we will add some code to show the list of currencies and their exchange rate.&lt;/p&gt;
&lt;p&gt;First step will be modifying the &lt;strong&gt;Startup.cs&lt;/strong&gt;&amp;nbsp;to initialize the services from the Domain:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;using Domain;

...

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor();
    services.AddSingleton&amp;lt;WeatherForecastService&amp;gt;();

    services.InitDomain();
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Next, we create a new Razor component to host the page with the list of currencies,&amp;nbsp;&lt;strong&gt;Pages/Currency.razor&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;@page "/currency"

@using Domain.Services
@using Domain.Model
@inject ICurrencyApi CurrencyService


&amp;lt;h1&amp;gt;Currency converter&amp;lt;/h1&amp;gt;

@if (rates == null)
{
    &amp;lt;p&amp;gt;&amp;lt;em&amp;gt;Loading...&amp;lt;/em&amp;gt;&amp;lt;/p&amp;gt;
    &amp;lt;p&amp;gt;@error&amp;lt;/p&amp;gt;
}
else
{
    &amp;lt;h3&amp;gt;1 @rates.Base is worth as of @rates.Date.ToString("d"):&amp;lt;/h3&amp;gt;
    &amp;lt;table class="table"&amp;gt;
        &amp;lt;thead&amp;gt;
            &amp;lt;tr&amp;gt;
                &amp;lt;th&amp;gt;Currency&amp;lt;/th&amp;gt;
                &amp;lt;th&amp;gt;Rate&amp;lt;/th&amp;gt;
            &amp;lt;/tr&amp;gt;
        &amp;lt;/thead&amp;gt;
        &amp;lt;tbody&amp;gt;
            @foreach (var rate in rates.RateList)
            {
                &amp;lt;tr&amp;gt;
                    &amp;lt;td&amp;gt;@rate.Key&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;@rate.Value&amp;lt;/td&amp;gt;
                &amp;lt;/tr&amp;gt;
            }
        &amp;lt;/tbody&amp;gt;
    &amp;lt;/table&amp;gt;
}

@code {
    private Rates rates;
    private string error;

    protected override async Task OnInitializedAsync()
    {
        var response = await CurrencyService.GetLatest();
        if (response.IsSuccessStatusCode)
        {
            rates = response.Content;
        }
        else
            error = response.Error.Content;
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;In this page, we first inject our domain service:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;@inject ICurrencyApi CurrencyService&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;During the component initialization,&amp;nbsp;&lt;strong&gt;OnInitializedAsync()&lt;/strong&gt;, we call the service to get the data:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;var response = await CurrencyService.GetLatest();&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;If the request is succesful, we initialize the local variable&amp;nbsp;&lt;strong&gt;rates&lt;/strong&gt;, which will be the one used to display the data on screen:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;rates = response.Content;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Finally, let's add a link in the menu to our newly created page, modifying&amp;nbsp;&lt;strong&gt;Shared/NavMenu.razor&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class="language-markup"&gt;&lt;code&gt;&amp;lt;li class="nav-item px-3"&amp;gt;
    &amp;lt;NavLink class="nav-link" href="currency"&amp;gt;
        &amp;lt;span class="oi oi-list-rich" aria-hidden="true"&amp;gt;&amp;lt;/span&amp;gt; Currency
    &amp;lt;/NavLink&amp;gt;
&amp;lt;/li&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;If everything goes fine, and we still have the app running with "&lt;code&gt;dotnet watch run&lt;/code&gt;", we can go back to the browser and we will see the new option in the menu. If not, we just launch the application and wait for the browser to run. Clicking on the menu, we should see the list of currencies exchange rates at the current date:&lt;/p&gt;
&lt;p style="text-align: center;"&gt;&lt;img src="https://sergiwebstorage.blob.core.windows.net/blogfiles/Posts\files\Image4_637495089054350184.png" alt="Image4.png" width="826" height="421" /&gt;&lt;/p&gt;
&lt;p style="text-align: center;"&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Summary&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Blazor is becoming a very interesting framework to develop SPA and dynamic web applications, same style as React, Angular, etc. specially for developers specialized on backend and C#.&lt;br /&gt;&lt;br /&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Refit&lt;/strong&gt;&amp;nbsp;is a library to dynamically create REST APIs clients with minimum effort, but very powerful at the same time.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;In the following posts, I will keep showing some features from Blazor and RefitEn pr&amp;oacute;ximos posts seguir&amp;eacute; mostrando algunas funcionalidades de Blazor y Refit, going deeper a bit more on this sample application to calculate currency exchange rates.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
  <author>Sergi Gisbert</author>
  <category>blazor</category>
  <category>dotnet core</category>
  <category>refit</category>
  <category>pwa</category>
  <category>english</category>
  <guid isPermaLink="false">https://www.sergigisbert.com/blog/how-to-make-an-external-api-request-in-blazor-using-refit/</guid>
  <pubDate>Sun, 28 Feb 2021 12:01:29 GMT</pubDate>
</item>
<item>
  <title>Cómo hacer una petición a un API externa con Blazor y Refit</title>
  <link>https://www.sergigisbert.com/blog/como-hacer-una-peticion-a-un-api-externa-con-blazor-y-refit/</link>
  <description>&lt;p&gt;&lt;strong&gt;Blazor&lt;/strong&gt; es el nuevo framework de desarrollo para crear SPA que ofrece Microsoft y que est&amp;aacute; teniendo mucho crecimiento en los &amp;uacute;ltimos tiempos. En este art&amp;iacute;culo haremos una peque&amp;ntilde;a demostraci&amp;oacute;n de c&amp;oacute;mo hacer una llamada a un API externa y mostrar los datos recibidos, utilizando &lt;strong&gt;Refit&lt;/strong&gt; de una manera muy sencilla.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Blazor&lt;/strong&gt; permite crear aplicaciones en el lado del cliente con &lt;strong&gt;C#&lt;/strong&gt;, por lo que consigue que muchos desarrolladores que nos consideramos m&amp;aacute;s de Backend, podamos dar el salto a &lt;strong&gt;Full-Stack&lt;/strong&gt; sin necesidad de aprender otros frameworks como Angular o React. As&amp;iacute;mismo, ya existen varias librer&amp;iacute;as de controles de UI para Blazor, incluso algunas gratuitas como las de &lt;a href="https://blazor.radzen.com/" target="_blank" rel="noopener"&gt;Radzen&lt;/a&gt;. La &amp;uacute;ltima aplicaci&amp;oacute;n real que he desarrollado con Blazor la pod&amp;eacute;is ver en&amp;nbsp;&lt;a href="https://www.saboraemocion.com/" target="_blank" rel="noopener"&gt;https://www.saboraemocion.com/&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;No es el objetivo de este post hacer una introducci&amp;oacute;n a Blazor, ya que existe muy buena documentaci&amp;oacute;n y tutoriales oficiales que recomiendo seguir. Pod&amp;eacute;is empezar en&amp;nbsp;&lt;a href="https://dotnet.microsoft.com/apps/aspnet/web-apps/blazor" target="_blank" rel="noopener"&gt;https://dotnet.microsoft.com/apps/aspnet/web-apps/blazor&lt;/a&gt;.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;En cambio, voy a aprovechar un proyecto con Blazor para escribir sobre &lt;a href="https://github.com/reactiveui/refit" target="_blank" rel="noopener"&gt;Refit&lt;/a&gt;, una librer&amp;iacute;a que nos permite crear autom&amp;aacute;ticamente un cliente para consumir un API REST externa a partir de la definici&amp;oacute;n de un Interface. &lt;strong&gt;Refit&lt;/strong&gt; se encarga del resto: comunicaci&amp;oacute;n Http, autenticaci&amp;oacute;n, cabeceras, serializaci&amp;oacute;n, conversi&amp;oacute;n de tipos, etc. Usaremos Refit para crear un peque&amp;ntilde;o conversor de moneda, con los datos ofrecidos por la API gratuita&amp;nbsp;&lt;a href="https://api.exchangeratesapi.io/" target="_blank" rel="noopener"&gt;https://api.exchangeratesapi.io/&lt;/a&gt;&amp;nbsp;(ver detalles del servicio en &lt;a href="https://exchangeratesapi.io/" target="_blank" rel="noopener"&gt;https://exchangeratesapi.io/&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;El c&amp;oacute;digo fuente de ejemplo lo pod&amp;eacute;is encontrar en&amp;nbsp;&lt;a href="https://github.com/sgisbert/blazor-currencyexchange" target="_blank" rel="noopener"&gt;https://github.com/sgisbert/blazor-currencyexchange&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Configuraci&amp;oacute;n inicial&lt;/h2&gt;
&lt;p&gt;Para este ejemplo sencillo, crearemos una aplicaci&amp;oacute;n SPA con &lt;strong&gt;Blazor Server&lt;/strong&gt; con .Net 5. Tambi&amp;eacute;n se puede desarrollar con un modelo basado en cliente con &lt;strong&gt;Blazor WebAssembly&lt;/strong&gt;. Pod&amp;eacute;is ver las diferencias entre ambos modos de hospedaje en&amp;nbsp;&lt;a href="https://docs.microsoft.com/aspnet/core/blazor/hosting-models" target="_blank" rel="noopener"&gt;https://docs.microsoft.com/aspnet/core/blazor/hosting-models&lt;/a&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Para crear nuestra aplicaci&amp;oacute;n, podemos usar el asistente de Visual Studio, o simplemente, siguiendo los pasos del &lt;a href="https://dotnet.microsoft.com/learn/aspnet/blazor-tutorial/intro" target="_blank" rel="noopener"&gt;tutorial de Blazor&lt;/a&gt;, lanzar el siguiente comando desde PowerShell:&lt;/p&gt;
&lt;pre class="language-markup"&gt;&lt;code&gt;dotnet new blazorserver -o BlazorApp&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Y para comprobar que todo funciona, entramos en la carpeta "BlazorApp" que se ha generado y ejecutamos:&lt;/p&gt;
&lt;pre class="language-markup"&gt;&lt;code&gt;dotnet watch run&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;que compilar&amp;aacute; y ejecutar&amp;aacute; la aplicaci&amp;oacute;n, y volver&amp;aacute; a compilar y reiniciarla cada vez que el c&amp;oacute;digo fuente cambie. Para detenerla basta con pulsar &lt;strong&gt;Ctrl&lt;/strong&gt;+&lt;strong&gt;C&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Cuando termine de compilar mostrar&amp;aacute; que est&amp;aacute; escuchando en http://localhost:5001 y se abrir&amp;aacute; el navegador con esa direcci&amp;oacute;n, mostrando la aplicaci&amp;oacute;n que acabamos de crear:&lt;/p&gt;
&lt;p style="text-align: center;"&gt;&lt;img src="https://sergiwebstorage.blob.core.windows.net/blogfiles/Posts\files\Image1_637495089046259032.png" alt="Image1.png" width="929" height="564" /&gt;&lt;/p&gt;
&lt;p style="text-align: center;"&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;A&amp;ntilde;adiendo la l&amp;oacute;gica de negocio&lt;/h2&gt;
&lt;p&gt;El objetivo de este ejemplo ser&amp;aacute; listar los valores de cambio de monedas disponibles para el d&amp;iacute;a de hoy. Para ello, haremos una llamada al endpoint&amp;nbsp;&lt;strong&gt;https://api.exchangeratesapi.io/latest&lt;/strong&gt;, que nos devuelve un objeto JSON como este:&amp;nbsp;&lt;/p&gt;
&lt;pre class="language-javascript"&gt;&lt;code&gt;{"rates":{"CAD":1.5307,"HKD":9.4121,"ISK":155.6,"PHP":58.846,"DKK":7.4368,"HUF":358.5,"CZK":25.849,"AUD":1.5445,"RON":4.8758,"SEK":10.033,"IDR":17094.81,"INR":88.0145,"BRL":6.5633,"RUB":89.6089,"HRK":7.578,"JPY":127.81,"THB":36.386,"CHF":1.0851,"SGD":1.6059,"PLN":4.483,"BGN":1.9558,"TRY":8.447,"CNY":7.8318,"NOK":10.2095,"NZD":1.6642,"ZAR":17.7391,"USD":1.2139,"MXN":24.7094,"ILS":3.97,"GBP":0.86508,"KRW":1339.59,"MYR":4.9048},"base":"EUR","date":"2021-02-19"}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Donde tenemos los diferentes precios de cada moneda con respecto al Euro para la &amp;uacute;ltima fecha publicada.&lt;/p&gt;
&lt;p&gt;Lo primero que haremos ser&amp;aacute; crear un nuevo proyecto en la soluci&amp;oacute;n para albergar nuestra l&amp;oacute;gica de negocio. Esto no es imprescindible para este ejemplo, pero ayuda a mantener las buenas pr&amp;aacute;cticas ;). Para ello, creamos una nueva librer&amp;iacute;a basada en .Net 5 a la soluci&amp;oacute;n, y la llamaremos "Domain". En t&amp;eacute;rminos de la metodolog&amp;iacute;a "Domain Driven Development" (DDD), esta ser&amp;aacute; nuestra capa de Dominio:&lt;/p&gt;
&lt;p style="text-align: center;"&gt;&lt;img src="https://sergiwebstorage.blob.core.windows.net/blogfiles/Posts\files\Image3_637495089051827731.png" alt="Image3.png" width="343" height="80" /&gt;&lt;/p&gt;
&lt;p&gt;El c&amp;oacute;digo fuente completo de este paso lo puedes encontrar en &lt;a href="https://github.com/sgisbert/blazor-currencyexchange/tree/4c7a62f6b07ccdcf406cee98fbe0afd50e87ed33" target="_blank" rel="noopener"&gt;GitHub&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Una vez tenemos el nuevo proyecto, empezaremos creando el modelo de datos con el que vamos a trabajar. Para generar el modelo en C#, podemos usar una herramienta como&amp;nbsp;&lt;a href="https://app.quicktype.io/" target="_blank" rel="noopener"&gt;https://app.quicktype.io/&lt;/a&gt;, que a partir del JSON anterior nos va a generar una clase completa en C#, incluso con la opci&amp;oacute;n de a&amp;ntilde;adir m&amp;eacute;todos auxiliares para serializar y deserializar los datos:&lt;/p&gt;
&lt;p style="text-align: center;"&gt;&lt;img src="https://sergiwebstorage.blob.core.windows.net/blogfiles/Posts\files\image2_637495089052883030.png" alt="image2.png" width="1116" height="792" /&gt;&lt;/p&gt;
&lt;p&gt;A&amp;ntilde;adimos el c&amp;oacute;digo generado a la clase &lt;strong&gt;Model/Rates.cs&amp;nbsp;&lt;/strong&gt;(necesitaremos a&amp;ntilde;adir una referencia al paquete de Nuget &lt;strong&gt;Newtonsoft.Json&lt;/strong&gt;):&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;namespace Domain.Model
{
    using System;
    using System.Collections.Generic;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    public partial class Rates
    {
        [JsonProperty("rates")]
        public Dictionary&amp;lt;string, double&amp;gt; RateList { get; set; }

        [JsonProperty("base")]
        public string Base { get; set; }

        [JsonProperty("date")]
        public DateTimeOffset Date { get; set; }
    }

    public partial class Rates
    {
        public static Rates FromJson(string json) =&amp;gt; JsonConvert.DeserializeObject&amp;lt;Rates&amp;gt;(json, Converter.Settings);
    }

    public static class Serialize
    {
        public static string ToJson(this Rates self) =&amp;gt; JsonConvert.SerializeObject(self, Converter.Settings);
    }

    internal static class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters = {
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
        };
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A continuaci&amp;oacute;n, usaremos&amp;nbsp;&lt;strong&gt;Refit&lt;/strong&gt; para definir el servicio que realice el acceso a la API. Para ello, primero incluimos el paquete de Nuget&amp;nbsp;&lt;strong&gt;Refit.HttpClientFactory&lt;/strong&gt; en nuestra soluci&amp;oacute;n (&lt;span style="color: #808080;"&gt;&lt;em&gt;&lt;strong&gt;Nota&lt;/strong&gt;: en el momento de escribir este ejemplo, usamos la versi&amp;oacute;n 5.1.2 de Refit. Si instalas la versi&amp;oacute;n 6.x puede que no funcione correctamente porque se ha cambiado el motor de serializaci&amp;oacute;n por defecto de Newtonsoft.Json a System.Text.Json. Recomiendo instalar la versi&amp;oacute;n de este ejemplo para seguirlo sin problemas, pero usar la &amp;uacute;ltima para nuevos desarrollos&lt;/em&gt;&lt;/span&gt;)&lt;/p&gt;
&lt;p&gt;A&amp;ntilde;adimos el siguiente Interface al proyecto de Domain &lt;strong&gt;Services/ICurrencyApi.cs&lt;/strong&gt;:&amp;nbsp;&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;using Domain.Model;
using Refit;
using System.Threading.Tasks;

namespace Domain.Services
{
    [Headers("Content-Type: application/json")]
    public interface ICurrencyApi
    {
        [Get("/latest")]
        Task&amp;lt;ApiResponse&amp;lt;Rates&amp;gt;&amp;gt; GetLatest();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Donde definimos la llamada al endpoint "latest" de la API, que nos va a devolver un objeto "&lt;strong&gt;ApiResponse&amp;lt;Rates&amp;gt;&lt;/strong&gt;", donde &lt;em&gt;ApiResponse&lt;/em&gt; contendr&amp;aacute; informaci&amp;oacute;n de la petici&amp;oacute;n (http response code, errores, etc. y el contenido de la misma, que es nuestro objeto de negocio, &lt;em&gt;Rates&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Seguidamente, a&amp;ntilde;adiremos el servicio que har&amp;aacute; uso del servicio de Refit, &lt;strong&gt;Services/ICurrencyService.cs&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;using Domain.Model;
using Refit;
using System.Threading.Tasks;

namespace Domain.Services
{
    public interface ICurrencyService
    {
        Task&amp;lt;ApiResponse&amp;lt;Rates&amp;gt;&amp;gt; GetLatest();
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;y su implementaci&amp;oacute;n,&amp;nbsp;&lt;strong&gt;Services/CurrencyService.cs&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;using Domain.Model;
using Refit;
using System.Threading.Tasks;

namespace Domain.Services
{
    public class CurrencyService : ICurrencyService
    {
        private readonly ICurrencyApi _api;

        public CurrencyService(ICurrencyApi api)
        {
            _api = api;
        }

        public async Task&amp;lt;ApiResponse&amp;lt;Rates&amp;gt;&amp;gt; GetLatest()
        {
            return await _api.GetLatest();
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Finalmente, a&amp;ntilde;adiremos una clase a nuestra librer&amp;iacute;a que se encargue de inicializar los servicios que hemos creado, para que la inyecci&amp;oacute;n de dependencias sea capaz de inicializarlos correctamente,&amp;nbsp;&lt;strong&gt;DomainStartup.cs&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;using Domain.Services;
using Microsoft.Extensions.DependencyInjection;
using Refit;
using System;

namespace Domain
{
    public static class DomainStartup
    {
        public static void InitDomain(this IServiceCollection services)
        {
            services.AddScoped&amp;lt;ICurrencyService, CurrencyService&amp;gt;();

            services.AddRefitClient&amp;lt;ICurrencyApi&amp;gt;()
                    .ConfigureHttpClient(c =&amp;gt; c.BaseAddress = new Uri("https://api.exchangeratesapi.io/"))
                    .SetHandlerLifetime(TimeSpan.FromMinutes(2));
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;En este caso, inicializamos nuestro&amp;nbsp;&lt;strong&gt;CurrencyService&lt;/strong&gt;, y hacemos uso de la extensi&amp;oacute;n&amp;nbsp;&lt;strong&gt;AddRefitClient&lt;/strong&gt; para indicarle a Refit los par&amp;aacute;metros de inicializaci&amp;oacute;n del API, como la URL base del servicio.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Usamos la l&amp;oacute;gica en la aplicaci&amp;oacute;n Blazor&lt;/h2&gt;
&lt;p&gt;Hasta el momento no hemos modificado para nada la aplicaci&amp;oacute;n Blazor que hemos creado al principio. Ahora a&amp;ntilde;adiremos el c&amp;oacute;digo para mostrar el listado de monedas y su tipo de cambio.&lt;/p&gt;
&lt;p&gt;Lo primero que hacemos es modificar&amp;nbsp;&lt;strong&gt;Startup.cs&lt;/strong&gt; para inicializar los servicios que hemos creado en el Dominio:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;using Domain;

...

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor();
    services.AddSingleton&amp;lt;WeatherForecastService&amp;gt;();

    services.InitDomain();
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;A continuaci&amp;oacute;n, creamos un nuevo componente razor que albergar&amp;aacute; la p&amp;aacute;gina con el listado de monedas,&amp;nbsp;&lt;strong&gt;Pages/Currency.razor&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;@page "/currency"

@using Domain.Services
@using Domain.Model
@inject ICurrencyApi CurrencyService


&amp;lt;h1&amp;gt;Currency converter&amp;lt;/h1&amp;gt;

@if (rates == null)
{
    &amp;lt;p&amp;gt;&amp;lt;em&amp;gt;Loading...&amp;lt;/em&amp;gt;&amp;lt;/p&amp;gt;
    &amp;lt;p&amp;gt;@error&amp;lt;/p&amp;gt;
}
else
{
    &amp;lt;h3&amp;gt;1 @rates.Base is worth as of @rates.Date.ToString("d"):&amp;lt;/h3&amp;gt;
    &amp;lt;table class="table"&amp;gt;
        &amp;lt;thead&amp;gt;
            &amp;lt;tr&amp;gt;
                &amp;lt;th&amp;gt;Currency&amp;lt;/th&amp;gt;
                &amp;lt;th&amp;gt;Rate&amp;lt;/th&amp;gt;
            &amp;lt;/tr&amp;gt;
        &amp;lt;/thead&amp;gt;
        &amp;lt;tbody&amp;gt;
            @foreach (var rate in rates.RateList)
            {
                &amp;lt;tr&amp;gt;
                    &amp;lt;td&amp;gt;@rate.Key&amp;lt;/td&amp;gt;
                    &amp;lt;td&amp;gt;@rate.Value&amp;lt;/td&amp;gt;
                &amp;lt;/tr&amp;gt;
            }
        &amp;lt;/tbody&amp;gt;
    &amp;lt;/table&amp;gt;
}

@code {
    private Rates rates;
    private string error;

    protected override async Task OnInitializedAsync()
    {
        var response = await CurrencyService.GetLatest();
        if (response.IsSuccessStatusCode)
        {
            rates = response.Content;
        }
        else
            error = response.Error.Content;
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;En esta p&amp;aacute;gina, primero estamos inyectando nuestro servicio de dominio:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;@inject ICurrencyApi CurrencyService&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Durante la inicializaci&amp;oacute;n del componente,&amp;nbsp;&lt;strong&gt;OnInitializedAsync()&lt;/strong&gt;, llamamos al servicio externo para obtener los datos:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;var response = await CurrencyService.GetLatest();&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Si la llamada ha sido correcta, inicializamos el valor de la variable local&amp;nbsp;&lt;strong&gt;rates&lt;/strong&gt;, que ser&amp;aacute; la que utilicemos para presentar los datos en pantalla:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;rates = response.Content;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Por &amp;uacute;ltimo, vamos a a&amp;ntilde;adir un enlace en el men&amp;uacute; a nuestra nueva p&amp;aacute;gina, modificando&amp;nbsp;&lt;strong&gt;Shared/NavMenu.razor&lt;/strong&gt;:&lt;/p&gt;
&lt;pre class="language-markup"&gt;&lt;code&gt;&amp;lt;li class="nav-item px-3"&amp;gt;
    &amp;lt;NavLink class="nav-link" href="currency"&amp;gt;
        &amp;lt;span class="oi oi-list-rich" aria-hidden="true"&amp;gt;&amp;lt;/span&amp;gt; Currency
    &amp;lt;/NavLink&amp;gt;
&amp;lt;/li&amp;gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Si todo ha ido bien, y seguimos teniendo la aplicaci&amp;oacute;n lanzada con "&lt;code&gt;dotnet watch run&lt;/code&gt;", volvemos al navegador y veremos la nueva opci&amp;oacute;n en el men&amp;uacute;. Si no, lanzamos la aplicaci&amp;oacute;n y esperamos a que se cargue en el navegador. Al pulsar sobre el men&amp;uacute;, veremos nuestro listado de monedas frente al euro en la fecha de hoy:&lt;/p&gt;
&lt;p style="text-align: center;"&gt;&lt;img src="https://sergiwebstorage.blob.core.windows.net/blogfiles/Posts\files\Image4_637495089054350184.png" alt="Image4.png" width="826" height="421" /&gt;&lt;/p&gt;
&lt;p style="text-align: center;"&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Conclusiones&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Blazor se est&amp;aacute; convirtiendo en un framework muy interesante para el desarrollo de SPA y aplicaciones web din&amp;aacute;micas, al estilo de Angular, React, etc. especialmente para los desarrolladores especializados en backend y C#.&lt;br /&gt;&lt;br /&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Refit&lt;/strong&gt;&amp;nbsp;es una librer&amp;iacute;a para crear din&amp;aacute;micamente clientes de APIs REST sin ning&amp;uacute;n esfuerzo, pero muy potente a su vez.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;En pr&amp;oacute;ximos posts seguir&amp;eacute; mostrando algunas funcionalidades de Blazor y Refit, profundizando un poco m&amp;aacute;s en este ejemplo de aplicaci&amp;oacute;n calcular los tipos de cambio entre monedas.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
  <author>Sergi Gisbert</author>
  <category>blazor</category>
  <category>dotnet core</category>
  <category>refit</category>
  <category>pwa</category>
  <guid isPermaLink="false">https://www.sergigisbert.com/blog/como-hacer-una-peticion-a-un-api-externa-con-blazor-y-refit/</guid>
  <pubDate>Sat, 20 Feb 2021 12:07:56 GMT</pubDate>
</item>
<item>
  <title>Parallel programming in C# with class Parallel</title>
  <link>https://www.sergigisbert.com/blog/parallel-programming-in-c-with-class-parallel/</link>
  <description>&lt;p&gt;&lt;em style="color: #808080;"&gt;Disclaimer: the methods and code examples in this article are the fruit of my own investigation and self learning, and in no means these are ready to be used in a real, production environment. Use at your own risk. To learn more about parallel and synchronous programming, I recommend reading the official documentation at:&amp;nbsp;&lt;a href="https://docs.microsoft.com/dotnet/standard/parallel-processing-and-concurrency" target="_blank" rel="noopener"&gt;https://docs.microsoft.com/dotnet/standard/parallel-processing-and-concurrency&lt;/a&gt;&amp;nbsp;&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="color: #993300;"&gt;&lt;em&gt;This post is part of a series of 3 articles about performace improvement with parallel programming:&lt;/em&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="color: #993300;"&gt;&lt;em&gt;1. &lt;a style="color: #993300;" href="https://www.sergigisbert.com/blog/improve-the-performance-with-asynchronous-functions-to-run-processes-in-parallel/" target="_blank" rel="noopener"&gt;Improve the performance with asynchronous functions to run processes in parallel&lt;/a&gt;&lt;/em&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: #993300;"&gt;&lt;em&gt;2. &lt;a style="color: #993300;" href="https://www.sergigisbert.com/blog/make-use-of-concurrentbag-to-store-the-results-from-asynchronous-processes/" target="_blank" rel="noopener"&gt;Make use of ConcurrentBag to store the results from asynchronous processes&lt;/a&gt;&lt;/em&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: #993300;"&gt;&lt;em&gt;3. Parallel programming in C# with class Parallel (this article)&lt;/em&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Following up with the series of posts about async programming and performance improvements using Tasks for process parallelization, in this one I am introducing a new option, using &lt;em&gt;Parallel&lt;/em&gt; class available in .Net, and I will compare it with the previous examples, where we run a process that returns a list of 10 random numbers between 1 and 100, and we cut it down to&amp;nbsp;&lt;strong&gt;0,6s&lt;/strong&gt;&amp;nbsp;execution time, from the starting&amp;nbsp;&lt;strong&gt;2s&lt;/strong&gt;&amp;nbsp;of the synchronous process:&lt;/p&gt;
&lt;pre class="language-markup"&gt;&lt;code&gt;Result: 82,83,88,99,57,71,13,54,18,40
Completed: 00:00:00.6276547&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can find the source code of this examples on Github:&amp;nbsp;&lt;a href="https://github.com/sgisbert/parallelization" target="_blank" rel="noopener"&gt;https://github.com/sgisbert/parallelization&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;At this examples, we used&amp;nbsp;&lt;em&gt;Task.Run()&lt;/em&gt;&amp;nbsp;to execute a process in a new thread. It is important to understand that the use of&amp;nbsp;&lt;em&gt;Task&lt;/em&gt;&amp;nbsp;to create new threads is limited to the number of cores available, and the excesive use of these can lead to a not so efficient use of system resources. To better understand these concepts, I recommend further reading:&amp;nbsp;&lt;a href="https://www.pluralsight.com/guides/using-task-run-async-await#module-knowthenatureofyourasynchronousoperation" target="_blank" rel="noopener"&gt;https://www.pluralsight.com/guides/using-task-run-async-await#module-knowthenatureofyourasynchronousoperation&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The use of&amp;nbsp;&lt;em&gt;async/await&lt;/em&gt;&amp;nbsp;pattern is specially recommended with libraries or API calls that already offer async methods, without the need to use &lt;em&gt;Task.Run()&lt;/em&gt;&amp;nbsp;to create them. Good examples of this are &lt;em&gt;HttpClient&lt;/em&gt;&amp;nbsp;or&amp;nbsp;&lt;em&gt;FileStream&lt;/em&gt;, that offer I/O async methods and we can take full benefit of async programming.&lt;/p&gt;
&lt;p&gt;If still we have a use case like in the example, where you need to execute the same logic over several objects, we can use the class&amp;nbsp;&lt;em&gt;Parallel&lt;/em&gt;, and see how it performs, in comparison with &lt;em&gt;Task.WaitAll()&lt;/em&gt;&amp;nbsp;or&amp;nbsp;&lt;em&gt;Task.WhenAll().&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Task.WaitAll() vs Task.WhenAll()&lt;/h2&gt;
&lt;p&gt;There are two different ways to wait for all our tasks to complete:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;await Task.WhenAll(tasks.ToArray());&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and&amp;nbsp;&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;Task.WaitAll(tasks.ToArray());&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;and it is interesting to know the differences between both. In terms of performance, the process takes a very similar amount of time to complete: 0,6s, but there are some aspects worth to be noted:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Task.WaitAll()&lt;/em&gt;&amp;nbsp;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The main UI execution thread is blocked until all the tasks are completed, so it does not return a&amp;nbsp;&lt;em&gt;Task&lt;/em&gt;. This means that if we have a UI dependant application, it could freeze until the execution ends.&lt;/li&gt;
&lt;li&gt;If there are any exceptions thrown, it will throw an &lt;em&gt;AggregateException&lt;/em&gt; with all the exceptions together.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;em&gt;await Task.WhenAll()&lt;/em&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The main thread is not blocked, so this would be the recommended approach for a UI application and async methods, as it actually returns a&amp;nbsp;&lt;em&gt;Task&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;If there are any exceptions, only the first one is returned.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In this article, you can explore deeper the differences between both methods:&amp;nbsp;&lt;a href="https://www.infoworld.com/article/3152735/when-to-use-taskwaitall-vs-taskwhenall-in-net.html" target="_blank" rel="noopener"&gt;https://www.infoworld.com/article/3152735/when-to-use-taskwaitall-vs-taskwhenall-in-net.html&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Using Parallel class&lt;/h2&gt;
&lt;p&gt;Another way to make use of parallel programming advantages, is with class&amp;nbsp;&lt;em&gt;Parallel&lt;/em&gt;&amp;nbsp;in .Net (more info in the&amp;nbsp;&lt;a href="https://docs.microsoft.com/dotnet/api/system.threading.tasks.parallel?view=net-5.0" target="_blank" rel="noopener"&gt;official documentation&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;First thing to do with our code will be to transform the process so it does not need to use&amp;nbsp;&lt;em&gt;Task.Run()&lt;/em&gt;, but keeping the compatibility with&amp;nbsp;&lt;em&gt;Task&lt;/em&gt;&amp;nbsp;to be able to compare both results. So, let's modify the method in the following way (&lt;a href="https://github.com/sgisbert/parallelization/blob/540ac5c9138c8549ee1ce87efb74948424309abc/src/Program.cs" target="_blank" rel="noopener"&gt;see full source code on GitHub&lt;/a&gt;):&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;private static async Task Process(int id, ConcurrentBag&amp;lt;int&amp;gt; cb)
{
    await Task.Run(() =&amp;gt;
    {
        CoreProcess(id, cb);
    });
}

private static void CoreProcess(int id, ConcurrentBag&amp;lt;int&amp;gt; cb)
{
    Stopwatch timer = new Stopwatch();
    timer.Start();
    Random random = new Random();
    Thread.Sleep(200);

    int number = random.Next(1, 100);
    cb.Add(number);

    Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] Process {id}: {timer.Elapsed}");
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;We also added the value of&amp;nbsp;&lt;em&gt;Thread.CurrentThread.ManagedThreadId&lt;/em&gt;&amp;nbsp;to the console output to check the Threads being created.&lt;/p&gt;
&lt;p&gt;This way, we can call our process both in sync or async way.&lt;/p&gt;
&lt;h3&gt;Parallel.ForEach()&lt;/h3&gt;
&lt;p&gt;Now we can add the following code, using&amp;nbsp;&lt;a href="https://docs.microsoft.com/dotnet/api/system.threading.tasks.parallel.foreach?view=net-5.0" target="_blank" rel="noopener"&gt;&lt;em&gt;Parallel.ForEach()&lt;/em&gt;&lt;/a&gt;&amp;nbsp;to run the synchronous process, but being parallelized (&lt;a href="https://github.com/sgisbert/parallelization/blob/04c243d2b4b50d69315fbd562bd2739f95627374/src/Program.cs" target="_blank" rel="noopener"&gt;see full source code on GitHub&lt;/a&gt;):&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;timer.Restart();
ConcurrentBag&amp;lt;int&amp;gt; cb2 = new ConcurrentBag&amp;lt;int&amp;gt;();
var sourceCollection = new List&amp;lt;int&amp;gt; { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Parallel.ForEach(sourceCollection, (id) =&amp;gt;
{
    CoreProcess(id, cb2);
});
Console.WriteLine($"Result: {string.Join(",", cb2)}");
Console.WriteLine($"Completed: {timer.Elapsed}");
Console.WriteLine();&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And let's compare the results:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Task.WaitAll()&lt;/em&gt;&lt;/p&gt;
&lt;pre class="language-markup"&gt;&lt;code&gt;[6] Process 2: 00:00:00.2028313
[5] Process 1: 00:00:00.2039001
[4] Process 0: 00:00:00.2063105
[7] Process 3: 00:00:00.2027921
[4] Process 5: 00:00:00.2006033
[7] Process 7: 00:00:00.2006397
[5] Process 6: 00:00:00.2006732
[6] Process 4: 00:00:00.2007073
[7] Process 8: 00:00:00.2001104
[5] Process 9: 00:00:00.2009985

Result: 15,49,52,76,90,1,71,67,37,23
Completed: 00:00:00.6398704
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Parallel.ForEach()&lt;/em&gt;&lt;/p&gt;
&lt;pre class="language-markup"&gt;&lt;code&gt;[6] Process 9: 00:00:00.2011420
[5] Process 3: 00:00:00.2012138
[1] Process 1: 00:00:00.2013376
[4] Process 7: 00:00:00.2011324
[7] Process 5: 00:00:00.2011974
[1] Process 2: 00:00:00.2004285
[4] Process 8: 00:00:00.2004063
[7] Process 6: 00:00:00.2005255
[6] Process 10: 00:00:00.2006825
[5] Process 4: 00:00:00.2006454
Result: 50,82,38,39,37,96,80,48,95,90
Completed: 00:00:00.4507518&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The task run with &lt;em&gt;Parallel&lt;/em&gt;&amp;nbsp;has decreased the time to&amp;nbsp;&lt;strong&gt;0,45s&lt;/strong&gt;&amp;nbsp;in front of the&amp;nbsp;&lt;strong&gt;0,6s&lt;/strong&gt;&amp;nbsp;of&amp;nbsp;&lt;em&gt;Task&lt;/em&gt;. We got a performance improvement without having to make use of &lt;em&gt;Task.Run(),&lt;/em&gt;&amp;nbsp;which could bring up potential problems with the use of system resources.&lt;/p&gt;
&lt;h3&gt;Parallel.Invoke()&lt;/h3&gt;
&lt;p&gt;&lt;em&gt;Parallel&lt;/em&gt;&amp;nbsp;offers also another alternative to execute parallel tasks, with method&amp;nbsp;&lt;em&gt;&lt;a href="https://docs.microsoft.com/dotnet/api/system.threading.tasks.parallel.invoke?view=net-5.0" target="_blank" rel="noopener"&gt;Invoke()&lt;/a&gt;&lt;/em&gt;. To test it, let's add the following code lines (&lt;a href="https://github.com/sgisbert/parallelization/blob/6019085440710a0345fe2ed2f4bc3c3a1f414619/src/Program.cs" target="_blank" rel="noopener"&gt;see full source code on Github&lt;/a&gt;):&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;timer.Restart();
ConcurrentBag&amp;lt;int&amp;gt; cb3 = new ConcurrentBag&amp;lt;int&amp;gt;();
List&amp;lt;Action&amp;gt; actions = new List&amp;lt;Action&amp;gt;();
foreach (var i in sourceCollection)
{
    actions.Add(() =&amp;gt; CoreProcess(i, cb3));
}
Parallel.Invoke(actions.ToArray());
Console.WriteLine($"Result: {string.Join(",", cb3)}");
Console.WriteLine($"Completed: {timer.Elapsed}");&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With the following results:&lt;/p&gt;
&lt;pre class="language-markup"&gt;&lt;code&gt;[4] Process 3: 00:00:00.2008078
[6] Process 4: 00:00:00.2008435
[5] Process 5: 00:00:00.2007954
[7] Process 2: 00:00:00.2008161
[1] Process 1: 00:00:00.2009441
[7] Process 8: 00:00:00.2001254
[5] Process 6: 00:00:00.2001896
[4] Process 7: 00:00:00.2001298
[8] Process 10: 00:00:00.2033235
[6] Process 9: 00:00:00.2089627
Result: 55,26,74,29,32,45,71,46,39,90
Completed: 00:00:00.4121676&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this case,&amp;nbsp;&lt;em&gt;Invoke()&lt;/em&gt;&amp;nbsp;reduces the time up to nearly&amp;nbsp;&lt;strong&gt;0,4s&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Conclusions&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Analize deeply each situation, understanding how async methods work and the differences between&amp;nbsp;&lt;em&gt;Task.WaitAll&lt;/em&gt;&amp;nbsp;y&amp;nbsp;&lt;em&gt;Task.WhenAll&lt;/em&gt;, to make use of them correctly on every situation.&lt;/li&gt;
&lt;li&gt;Know other alternatives like &lt;em&gt;Parallel&lt;/em&gt;&amp;nbsp;to improve the application performance.&lt;/li&gt;
&lt;li&gt;Don't take any of these examples for granted. Make your own performance tests and check on every case what solution works best for you&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
  <author>Sergi Gisbert</author>
  <category>c#</category>
  <category>.net</category>
  <category>dotnet core</category>
  <category>performance</category>
  <category>tips</category>
  <category>parallel</category>
  <category>english</category>
  <guid isPermaLink="false">https://www.sergigisbert.com/blog/parallel-programming-in-c-with-class-parallel/</guid>
  <pubDate>Sat, 13 Feb 2021 15:14:08 GMT</pubDate>
</item>
<item>
  <title>Programación paralela en C# con la clase Parallel</title>
  <link>https://www.sergigisbert.com/blog/programacion-paralela-en-c-con-la-clase-parallel/</link>
  <description>&lt;p&gt;&lt;span style="color: #808080;"&gt;&lt;em&gt;Disclaimer: los m&amp;eacute;todos y ejemplos de c&amp;oacute;digo de este art&amp;iacute;culo son fruto de mi propia investigaci&amp;oacute;n y aprendizaje aut&amp;oacute;nomo, y en ning&amp;uacute;n caso est&amp;aacute;n preparados para su utilizaci&amp;oacute;n en c&amp;oacute;digo real de producci&amp;oacute;n. El autor no se hace responsable del uso de estos ejemplos. Para m&amp;aacute;s informaci&amp;oacute;n sobre programaci&amp;oacute;n paralela y as&amp;iacute;ncrona y sus connotaciones, recomiendo acceder a la documentaci&amp;oacute;n oficial: &lt;a style="color: #808080;" href="https://docs.microsoft.com/dotnet/standard/parallel-processing-and-concurrency" target="_blank" rel="noopener"&gt;https://docs.microsoft.com/dotnet/standard/parallel-processing-and-concurrency&lt;/a&gt;&amp;nbsp;&lt;/em&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="color: #993300;"&gt;&lt;em&gt;Este post forma parte de una serie de 3 art&amp;iacute;culos sobre mejoras de rendimiento utilizando programaci&amp;oacute;n paralela:&lt;/em&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="color: #993300;"&gt;&lt;em&gt;1.&amp;nbsp;&lt;a style="color: #993300;" href="https://www.sergigisbert.com/blog/mejorar-el-rendimiento-con-funciones-asincronas-para-la-ejecucion-de-procesos-en-paralelo/" target="_blank" rel="noopener"&gt;Mejorar el rendimiento con funciones as&amp;iacute;ncronas para la ejecuci&amp;oacute;n de procesos en paralelo&lt;/a&gt;&lt;/em&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: #993300;"&gt;&lt;em&gt;2.&amp;nbsp;&lt;a style="color: #993300;" href="https://www.sergigisbert.com/blog/utilizar-concurrentbag-para-almacenar-el-resultado-de-metodos-asincronos/" target="_blank" rel="noopener"&gt;Utilizar ConcurrentBag para almacenar el resultado de m&amp;eacute;todos as&amp;iacute;ncronos&lt;/a&gt;&lt;/em&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: #993300;"&gt;&lt;em&gt;3. Programaci&amp;oacute;n paralela en C# con la clase Parallel (Este art&amp;iacute;culo)&lt;/em&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Siguiendo con la serie de posts dedicados a la programaci&amp;oacute;n as&amp;iacute;ncrona y a la mejora de rendimiento utilizando&amp;nbsp;&lt;em&gt;Task&lt;/em&gt;&amp;nbsp;para la paralelizaci&amp;oacute;n de procesos, en este caso introducimos una nueva posibilidad utilizando la clase&amp;nbsp;&lt;em&gt;Parallel&lt;/em&gt;&amp;nbsp;que nos ofrece .Net, y la comparamos con las ejecuciones anteriores, donde recordamos que se ejecutaba un proceso que nos devolv&amp;iacute;a una lista de 10 n&amp;uacute;meros aleatorios entre 1 y 100, y lo dejamos en unos &lt;strong&gt;0,6s&lt;/strong&gt; de tiempo de ejecuci&amp;oacute;n, frente a los &lt;strong&gt;2s&lt;/strong&gt; originales de un proceso s&amp;iacute;ncrono:&lt;/p&gt;
&lt;pre class="language-markup"&gt;&lt;code&gt;Result: 82,83,88,99,57,71,13,54,18,40
Completed: 00:00:00.6276547&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;El c&amp;oacute;digo fuente de ejemplo mostrado lo pod&amp;eacute;is encontrar en Github: &lt;a href="https://github.com/sgisbert/parallelization" target="_blank" rel="noopener"&gt;https://github.com/sgisbert/parallelization&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;En estos ejemplos, us&amp;aacute;bamos &lt;em&gt;Task.Run()&lt;/em&gt; para ejecutar el proceso en un nuevo hilo. Es importante entender que el uso de &lt;em&gt;Task&lt;/em&gt; para crear nuevos hilos de ejecuci&amp;oacute;n est&amp;aacute; limitado por el n&amp;uacute;mero de cores que tengamos en el procesador, y el uso excesivo de estos puede llevar a un uso poco eficiente de los recursos del sistema. Para entender m&amp;aacute;s estos conceptos, recomiendo leer este art&amp;iacute;culo:&amp;nbsp;&lt;a href="https://www.pluralsight.com/guides/using-task-run-async-await#module-knowthenatureofyourasynchronousoperation" target="_blank" rel="noopener"&gt;https://www.pluralsight.com/guides/using-task-run-async-await#module-knowthenatureofyourasynchronousoperation&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;El uso de &lt;em&gt;async/await&lt;/em&gt; es especialmente recomendable junto con librer&amp;iacute;as o APIs que ofrecen m&amp;eacute;todos as&amp;iacute;ncronos sin necesidad de acudir a &lt;em&gt;Task.Run()&lt;/em&gt; para crearlos. Buenos ejemplos de este caso son&amp;nbsp;&lt;em&gt;HttpClient&lt;/em&gt; o&amp;nbsp;&lt;em&gt;FileStream&lt;/em&gt;, que ofrecen m&amp;eacute;todos de I/O as&amp;iacute;ncronos donde se pueden aprovechar las virtudes de la programaci&amp;oacute;n as&amp;iacute;ncrona.&lt;/p&gt;
&lt;p&gt;Si a&amp;uacute;n as&amp;iacute; tenemos un caso como el del ejemplo, donde tenemos que realizar un mismo procesamiento sobre m&amp;uacute;ltiples instancias diferentes, podemos aprovechar la clase&amp;nbsp;&lt;em&gt;Parallel&lt;/em&gt;, y ver c&amp;oacute;mo se comporta en comparaci&amp;oacute;n con &lt;em&gt;Task.WaitAll()&lt;/em&gt; o&amp;nbsp;&lt;em&gt;Task.WhenAll().&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Task.WaitAll() vs Task.WhenAll()&lt;/h2&gt;
&lt;p&gt;Existen dos maneras de esperar a que todas nuestras tareas terminen de ejecutarse:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;await Task.WhenAll(tasks.ToArray());&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;y&amp;nbsp;&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;Task.WaitAll(tasks.ToArray());&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Y es interesante conocer la diferencia entre las dos. En t&amp;eacute;rminos de rendimiento, en ambos casos el proceso dura un tiempo similar: 0,6s, pero hay ciertos matices interesantes a conocer:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Task.WaitAll()&lt;/em&gt;&amp;nbsp;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Bloquea el thread principal de ejecuci&amp;oacute;n hasta que todas las tareas terminen, por lo que no devuelve una &lt;em&gt;Task&lt;/em&gt;. Esto significa que si tenemos una aplicaci&amp;oacute;n con UI, &amp;eacute;ste quedar&amp;aacute; bloqueado hasta que termine la ejecuci&amp;oacute;n&lt;/li&gt;
&lt;li&gt;Si se producen excepciones en una o varias tareas, lanzar&amp;aacute; una&amp;nbsp;&lt;em&gt;AggregateException&amp;nbsp;&lt;/em&gt;con todas las excepciones que se hayan producido&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;em&gt;await Task.WhenAll()&lt;/em&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;No bloquea el thread principal, por lo que ser&amp;iacute;a el m&amp;eacute;todo recomendado para aplicaci&amp;oacute;n con UI y m&amp;eacute;todos async, ya que s&amp;iacute; devuelve una&amp;nbsp;&lt;em&gt;Task&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;Si se producen excepciones, s&amp;oacute;lo lanzar&amp;aacute; la primera que ocurra.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;En este art&amp;iacute;culo se detalla con m&amp;aacute;s nivel de detalle las diferencias entre ambos m&amp;eacute;todos:&amp;nbsp;&lt;a href="https://www.infoworld.com/article/3152735/when-to-use-taskwaitall-vs-taskwhenall-in-net.html" target="_blank" rel="noopener"&gt;https://www.infoworld.com/article/3152735/when-to-use-taskwaitall-vs-taskwhenall-in-net.html&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Utilizando la clase Parallel&lt;/h2&gt;
&lt;p&gt;Otra manera de aprovechar las ventajas de la computaci&amp;oacute;n paralela, es utilizar la clase&amp;nbsp;&lt;em&gt;Parallel&lt;/em&gt; de .Net (m&amp;aacute;s info en la &lt;a href="https://docs.microsoft.com/dotnet/api/system.threading.tasks.parallel?view=net-5.0" target="_blank" rel="noopener"&gt;documentaci&amp;oacute;n oficial&lt;/a&gt;)&lt;/p&gt;
&lt;p&gt;Lo primero que haremos con nuestro c&amp;oacute;digo de ejemplo ser&amp;aacute; transformar nuestro proceso para que no necesite utilizar&amp;nbsp;&lt;em&gt;Task.Run()&lt;/em&gt;, pero manteniendo la compatibilidad con&amp;nbsp;&lt;em&gt;Task&lt;/em&gt; para comparar ambos resultados. Para ello, modificamos el m&amp;eacute;todo process de la siguiente manera (&lt;a href="https://github.com/sgisbert/parallelization/blob/540ac5c9138c8549ee1ce87efb74948424309abc/src/Program.cs" target="_blank" rel="noopener"&gt;ver archivo completo en GitHub&lt;/a&gt;):&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;private static async Task Process(int id, ConcurrentBag&amp;lt;int&amp;gt; cb)
{
    await Task.Run(() =&amp;gt;
    {
        CoreProcess(id, cb);
    });
}

private static void CoreProcess(int id, ConcurrentBag&amp;lt;int&amp;gt; cb)
{
    Stopwatch timer = new Stopwatch();
    timer.Start();
    Random random = new Random();
    Thread.Sleep(200);

    int number = random.Next(1, 100);
    cb.Add(number);

    Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] Process {id}: {timer.Elapsed}");
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Hemos a&amp;ntilde;adido tambi&amp;eacute;n el valor de&amp;nbsp;&lt;em&gt;Thread.CurrentThread.ManagedThreadId&lt;/em&gt; a la salida por consola para comprobar los Threads que se crean.&lt;/p&gt;
&lt;p&gt;De esta manera, podemos llamar a nuestro proceso tanto de manera as&amp;iacute;ncrona como s&amp;iacute;ncrona.&lt;/p&gt;
&lt;h3&gt;Parallel.ForEach()&lt;/h3&gt;
&lt;p&gt;A&amp;ntilde;adimos el siguiente c&amp;oacute;digo, que utiliza&amp;nbsp;&lt;a href="https://docs.microsoft.com/dotnet/api/system.threading.tasks.parallel.foreach?view=net-5.0" target="_blank" rel="noopener"&gt;&lt;em&gt;Parallel.ForEach()&lt;/em&gt;&lt;/a&gt; para lanzar el proceso s&amp;iacute;ncrono, pero usando paralelismo (&lt;a href="https://github.com/sgisbert/parallelization/blob/04c243d2b4b50d69315fbd562bd2739f95627374/src/Program.cs" target="_blank" rel="noopener"&gt;ver archivo completo en GitHub&lt;/a&gt;):&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;timer.Restart();
ConcurrentBag&amp;lt;int&amp;gt; cb2 = new ConcurrentBag&amp;lt;int&amp;gt;();
var sourceCollection = new List&amp;lt;int&amp;gt; { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Parallel.ForEach(sourceCollection, (id) =&amp;gt;
{
    CoreProcess(id, cb2);
});
Console.WriteLine($"Result: {string.Join(",", cb2)}");
Console.WriteLine($"Completed: {timer.Elapsed}");
Console.WriteLine();&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Y comparamos los resultados:&lt;/p&gt;
&lt;p&gt;&lt;em&gt;Task.WaitAll()&lt;/em&gt;&lt;/p&gt;
&lt;pre class="language-markup"&gt;&lt;code&gt;[6] Process 2: 00:00:00.2028313
[5] Process 1: 00:00:00.2039001
[4] Process 0: 00:00:00.2063105
[7] Process 3: 00:00:00.2027921
[4] Process 5: 00:00:00.2006033
[7] Process 7: 00:00:00.2006397
[5] Process 6: 00:00:00.2006732
[6] Process 4: 00:00:00.2007073
[7] Process 8: 00:00:00.2001104
[5] Process 9: 00:00:00.2009985

Result: 15,49,52,76,90,1,71,67,37,23
Completed: 00:00:00.6398704
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;Parallel.ForEach()&lt;/em&gt;&lt;/p&gt;
&lt;pre class="language-markup"&gt;&lt;code&gt;[6] Process 9: 00:00:00.2011420
[5] Process 3: 00:00:00.2012138
[1] Process 1: 00:00:00.2013376
[4] Process 7: 00:00:00.2011324
[7] Process 5: 00:00:00.2011974
[1] Process 2: 00:00:00.2004285
[4] Process 8: 00:00:00.2004063
[7] Process 6: 00:00:00.2005255
[6] Process 10: 00:00:00.2006825
[5] Process 4: 00:00:00.2006454
Result: 50,82,38,39,37,96,80,48,95,90
Completed: 00:00:00.4507518&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;La tarea ejecutada con&amp;nbsp;&lt;em&gt;Parallel&lt;/em&gt; ha bajado el tiempo a &lt;strong&gt;0,45s&lt;/strong&gt; frente a los &lt;strong&gt;0,6s&lt;/strong&gt; de&amp;nbsp;&lt;em&gt;Task&lt;/em&gt;. Hemos obtenido una mejora de rendimiento sin tener que ejecutar&amp;nbsp;&lt;em&gt;Task.Run()&lt;/em&gt; que puede ocasionar problemas con el uso de los recursos disponibles.&lt;/p&gt;
&lt;h3&gt;Parallel.Invoke()&lt;/h3&gt;
&lt;p&gt;&lt;em&gt;Parallel&lt;/em&gt; nos ofrece otra alternativa adicional para invocar tareas en paralelo, con el m&amp;eacute;todo&amp;nbsp;&lt;em&gt;&lt;a href="https://docs.microsoft.com/dotnet/api/system.threading.tasks.parallel.invoke?view=net-5.0" target="_blank" rel="noopener"&gt;Invoke()&lt;/a&gt;&lt;/em&gt;. Para probar su uso, a&amp;ntilde;adimos las siguientes l&amp;iacute;neas de c&amp;oacute;digo (&lt;a href="https://github.com/sgisbert/parallelization/blob/6019085440710a0345fe2ed2f4bc3c3a1f414619/src/Program.cs" target="_blank" rel="noopener"&gt;ver archivo completo en Github&lt;/a&gt;):&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;timer.Restart();
ConcurrentBag&amp;lt;int&amp;gt; cb3 = new ConcurrentBag&amp;lt;int&amp;gt;();
List&amp;lt;Action&amp;gt; actions = new List&amp;lt;Action&amp;gt;();
foreach (var i in sourceCollection)
{
    actions.Add(() =&amp;gt; CoreProcess(i, cb3));
}
Parallel.Invoke(actions.ToArray());
Console.WriteLine($"Result: {string.Join(",", cb3)}");
Console.WriteLine($"Completed: {timer.Elapsed}");&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Con los siguientes resultados:&lt;/p&gt;
&lt;pre class="language-markup"&gt;&lt;code&gt;[4] Process 3: 00:00:00.2008078
[6] Process 4: 00:00:00.2008435
[5] Process 5: 00:00:00.2007954
[7] Process 2: 00:00:00.2008161
[1] Process 1: 00:00:00.2009441
[7] Process 8: 00:00:00.2001254
[5] Process 6: 00:00:00.2001896
[4] Process 7: 00:00:00.2001298
[8] Process 10: 00:00:00.2033235
[6] Process 9: 00:00:00.2089627
Result: 55,26,74,29,32,45,71,46,39,90
Completed: 00:00:00.4121676&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;En este caso,&amp;nbsp;&lt;em&gt;Invoke()&lt;/em&gt; reduce el tiempo hasta casi &lt;strong&gt;0,4s&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Conclusiones&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Analiza bien cada situaci&amp;oacute;n, entendiendo c&amp;oacute;mo funcionan los m&amp;eacute;todos as&amp;iacute;ncronos y las diferencias entre&amp;nbsp;&lt;em&gt;Task.WaitAll&lt;/em&gt; y&amp;nbsp;&lt;em&gt;Task.WhenAll&lt;/em&gt;, para utilizarlos correctamente en cada caso&lt;/li&gt;
&lt;li&gt;Conoce otras alternativas como&amp;nbsp;&lt;em&gt;Parallel&lt;/em&gt; para mejorar el rendimiento de tus aplicaciones&lt;/li&gt;
&lt;li&gt;No te creas los resultados de estos ejemplos. Haz pruebas de rendimiento por ti mismo y comprueba en cada caso qu&amp;eacute; te funciona mejor&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
  <author>Sergi Gisbert</author>
  <category>c#</category>
  <category>dotnet core</category>
  <category>performance</category>
  <category>tips</category>
  <category>parallel</category>
  <guid isPermaLink="false">https://www.sergigisbert.com/blog/programacion-paralela-en-c-con-la-clase-parallel/</guid>
  <pubDate>Sun, 07 Feb 2021 11:59:45 GMT</pubDate>
</item>
<item>
  <title>Make use of ConcurrentBag to store the results from asynchronous processes</title>
  <link>https://www.sergigisbert.com/blog/make-use-of-concurrentbag-to-store-the-results-from-asynchronous-processes/</link>
  <description>&lt;p&gt;&lt;span style="color: #808080;"&gt;&lt;em&gt;Disclaimer: the methods and code examples in this article are the fruit of my own investigation and self learning, and in no means these are ready to be used in a real, production environment. Use at your own risk. To learn more about parallel and synchronous programming, I recommend reading the official documentation at: &lt;a href="https://docs.microsoft.com/dotnet/standard/parallel-processing-and-concurrency" target="_blank" rel="noopener"&gt;https://docs.microsoft.com/dotnet/standard/parallel-processing-and-concurrency&lt;/a&gt;&amp;nbsp;&lt;/em&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="color: #993300;"&gt;&lt;em&gt;This post is part of a series of 3 articles about performace improvement with parallel programming:&lt;/em&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&lt;span style="color: #993300;"&gt;&lt;em&gt;1. &lt;a style="color: #993300;" href="https://www.sergigisbert.com/blog/improve-the-performance-with-asynchronous-functions-to-run-processes-in-parallel/" target="_blank" rel="noopener"&gt;Improve the performance with asynchronous functions to run processes in parallel&lt;/a&gt;&lt;/em&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: #993300;"&gt;&lt;em&gt;2. Make use of ConcurrentBag to store the results from asynchronous processes&amp;nbsp;(this article)&lt;/em&gt;&lt;/span&gt;&lt;br /&gt;&lt;span style="color: #993300;"&gt;&lt;em&gt;3. &lt;a style="color: #993300;" href="https://www.sergigisbert.com/blog/parallel-programming-in-c-with-class-parallel/" target="_blank" rel="noopener"&gt;Parallel programming in C# with class Parallel&lt;/a&gt;&lt;/em&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;From my&amp;nbsp;&lt;a href="https://www.sergigisbert.com/blog/mejorar-el-rendimiento-con-funciones-asincronas-para-la-ejecucion-de-procesos-en-paralelo/"&gt;previous post&lt;/a&gt;&amp;nbsp;about parallelizing process execution, I am extending the sample there to show how we can get that different processes in parallel can combine their results into the same object, without the asynchronous execution being a problem. In this case, we are going to get all the results from the execution in the same data list.&lt;/p&gt;
&lt;p&gt;Source code in this article can be found on Github:&amp;nbsp;&lt;a href="https://github.com/sgisbert/parallelization" target="_blank" rel="noopener"&gt;https://github.com/sgisbert/parallelization&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Starting point&lt;/h2&gt;
&lt;p&gt;In the &lt;a href="https://www.sergigisbert.com/blog/mejorar-el-rendimiento-con-funciones-asincronas-para-la-ejecucion-de-procesos-en-paralelo/"&gt;previous post&lt;/a&gt;&amp;nbsp;we managed to reduce the processing time from 2 seconds down to 0.6 seconds, althoug actually our method was not returning any result. For this sample, I am modifying it to make it return a random number between 1 and 100, while we keep the delay to show the execution time.&lt;/p&gt;
&lt;p&gt;Let's modify the &lt;em&gt;Process()&lt;/em&gt;&amp;nbsp;method to return an integer (&lt;a href="https://github.com/sgisbert/parallelization/blob/c446abc728e858661d99be690e3c43833f11b6d3/src/Program.cs"&gt;see full file on Github&lt;/a&gt;):&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;private static async Task&amp;lt;int&amp;gt; Process(int id)
{
    var number = await Task&amp;lt;int&amp;gt;.Run(() =&amp;gt;
    {
        Stopwatch timer = new Stopwatch();
        timer.Start();
        Random random = new Random();
        Thread.Sleep(200);

        int number = random.Next(1,10);

        Console.WriteLine($"Process {id}: {timer.Elapsed}");
        return number;
    });
    return number;
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And add the necessary code to get the results in the main thread:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;List&amp;lt;Task&amp;lt;int&amp;gt;&amp;gt; tasks = new List&amp;lt;Task&amp;lt;int&amp;gt;&amp;gt;();
for (int i = 0; i &amp;lt; 10; i++)
{
    tasks.Add(Process(i));
}
Task.WaitAll(tasks.ToArray());

List&amp;lt;int&amp;gt; results = new List&amp;lt;int&amp;gt;();
foreach (var task in tasks)
{
    results.Add(task.Result);
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Note that changing the return type for &lt;em&gt;Process()&lt;/em&gt;&amp;nbsp;to&amp;nbsp;&lt;em&gt;Task&lt;strong&gt;&amp;lt;int&amp;gt;&lt;/strong&gt;&lt;/em&gt;, we also need to change it for the list where we are storing the tasks that are being executed to as well to&amp;nbsp;&lt;em&gt;List&amp;lt;Task&lt;strong&gt;&amp;lt;int&amp;gt;&lt;/strong&gt;&amp;gt;&lt;/em&gt;, so we can access later to the result with&amp;nbsp;&lt;em&gt;task.&lt;strong&gt;Result&lt;/strong&gt;&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;The execution result is as follows:&lt;/p&gt;
&lt;pre class="language-markup"&gt;&lt;code&gt;Process 0: 00:00:00.2077483
Process 1: 00:00:00.2076874
Process 3: 00:00:00.2074275
Process 2: 00:00:00.2057897
Process 7: 00:00:00.2097799
Process 6: 00:00:00.2101881
Process 5: 00:00:00.2103866
Process 4: 00:00:00.2109039
Process 9: 00:00:00.2004370
Process 8: 00:00:00.2006408

Result: 76,2,79,86,12,45,27,17,55,5
Completed: 00:00:00.6971794
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In this sample, we are processing all the results after all the tasks have finalized the execution. For this simple example, the second&amp;nbsp;&lt;em&gt;foreach&lt;/em&gt; loop has increased the execution time in almost one tenth, getting closer to 0.7s from the originally 0.6s. Imagine a more complex case where you should analyze hundreds or thousands results, it is possible you would lose most of the performance gains you got from parallelizing the process.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Getting the results already processed&lt;/h2&gt;
&lt;p&gt;So that we don't need to post process the results from the asynchronous methods in a loop, we can make use of concurrent data types, which are thread-safe, like&amp;nbsp;&lt;em&gt;&lt;a href="https://docs.microsoft.com/dotnet/api/system.collections.concurrent.blockingcollection-1" target="_blank" rel="noopener"&gt;ConcurrentBag&amp;lt;T&amp;gt;&lt;/a&gt;&lt;/em&gt;. There are also concurrent versions for &lt;em&gt;Dictionary, Queue&lt;/em&gt;&amp;nbsp;and&amp;nbsp;&lt;em&gt;Stack&lt;/em&gt;. With these data types, each process will add its results directly to the same ConcurrentBag as the others, so once back to the main thread, there's no need to loop over the results again.&lt;/p&gt;
&lt;p&gt;To do so, let's add the ConcurrentBag as a parameter to our &lt;em&gt;Process()&lt;/em&gt;&amp;nbsp;method (&lt;a href="https://github.com/sgisbert/parallelization/blob/1c15b608eb976170bdca07a2b574a6d77b3de0e5/src/Program.cs"&gt;see full file on Github&lt;/a&gt;):&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;private static async Task Process(int id, ConcurrentBag&amp;lt;int&amp;gt; cb)
{
    await Task.Run(() =&amp;gt;
    {
        Stopwatch timer = new Stopwatch();
        timer.Start();
        Random random = new Random();
        Thread.Sleep(200);

        int number = random.Next(1,100);
        cb.Add(number);

        Console.WriteLine($"Process {id}: {timer.Elapsed}");
    });
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So we don't need to return a &lt;em&gt;Task&amp;lt;int&amp;gt;&lt;/em&gt;, nor process again the results in the main thread, but we can make use of them directly from the ConcurrentBag:&lt;/p&gt;
&lt;pre class="language-csharp"&gt;&lt;code&gt;static async Task Main(string[] args)
{
    ConcurrentBag&amp;lt;int&amp;gt; cb = new ConcurrentBag&amp;lt;int&amp;gt;();
    Stopwatch timer = new Stopwatch();
    timer.Start();

    List&amp;lt;Task&amp;gt; tasks = new List&amp;lt;Task&amp;gt;();
    for (int i = 0; i &amp;lt; 10; i++)
    {
        tasks.Add(Process(i, cb));
    }
    Task.WaitAll(tasks.ToArray());

    Console.WriteLine();
    Console.WriteLine($"Result: {string.Join(",", cb)}");
    Console.WriteLine($"Completed: {timer.Elapsed}");
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Back to the results:&lt;/p&gt;
&lt;pre class="language-markup"&gt;&lt;code&gt;Process 1: 00:00:00.2029103
Process 2: 00:00:00.2028785
Process 0: 00:00:00.2029188
Process 3: 00:00:00.2028485
Process 5: 00:00:00.2007397
Process 7: 00:00:00.2007120
Process 6: 00:00:00.2007211
Process 4: 00:00:00.2008456
Process 9: 00:00:00.2001557
Process 8: 00:00:00.2007588

Result: 82,83,88,99,57,71,13,54,18,40
Completed: 00:00:00.6276547&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And we are back again to be closer to the 0.6 seconds than before, once we removed the unnecessary loop to process the results.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Conclusions&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;It is possible to execute processes in parallel and get the results grouped in the same object. This will avoid the need to post-process the results, which would add an unnecessary execution time.&lt;br /&gt;&lt;br /&gt;&lt;/li&gt;
&lt;li&gt;There are thread-safe data types for collections that can be used to store the results from asynchronous tasks, like &lt;em&gt;ConcurrentBag&lt;/em&gt;,&amp;nbsp;&lt;em&gt;ConcurrentDictionary&lt;/em&gt;,&amp;nbsp;&lt;em&gt;ConcurrentQueue&lt;/em&gt;&amp;nbsp;or&amp;nbsp;&lt;em&gt;ConcurrentStack&lt;/em&gt;. Learning how to use them will give us better options to improve our applications.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;</description>
  <author>Sergi Gisbert</author>
  <category>c#</category>
  <category>dotnet core</category>
  <category>performance</category>
  <category>tips</category>
  <category>async/await</category>
  <category>concurrentbag</category>
  <category>english</category>
  <guid isPermaLink="false">https://www.sergigisbert.com/blog/make-use-of-concurrentbag-to-store-the-results-from-asynchronous-processes/</guid>
  <pubDate>Sat, 30 Jan 2021 11:46:00 GMT</pubDate>
</item></channel>
</rss>