Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Challenge: Preventing Program Freezes Using Threading | Threading
C# Desktop Development with .NET MAUI

Challenge: Preventing Program Freezes Using Threading

Desliza para mostrar el menú

Task Description

Hint
expand arrow

Statements related to UI updates are best to execute in the Main Thread.

Solution
expand arrow
using Microsoft.Maui.Controls.Shapes;
using System.Globalization;
using System.Net.Http;

namespace MauiApp1
{
    public class apiEvent
    {
        public delegate void apiEventHandler(object sender, apiEventArgs e);

        public event apiEventHandler? OnResponse;

        public void OnApiResponse(string content)
        {
            apiEventHandler? handler = OnResponse;

            if (handler != null)
            {
                handler(this, new apiEventArgs(content));
            }
        }
    }

    public class apiEventArgs : EventArgs
    {
        public string Link { get; }

        public apiEventArgs(string content)
        {
            this.Link = content;
        }
    }

    public partial class MainPage : ContentPage
    {
        public apiEvent apiService = new apiEvent();

        Thread? mainTimer;
        Thread? getRequestThread;
        long ticks;

        public MainPage()
        {
            InitializeComponent();

            getImageButton.Clicked += GetImage;
            apiService.OnResponse += SetImage;

            ticks = 0;
            mainTimer = new Thread(new ThreadStart(timerUpdate));
            mainTimer.Start();
        }

        public void timerUpdate()
        {
            while (true)
            {
                ticks++;
                Thread.Sleep(50);
                MainThread.BeginInvokeOnMainThread(() => {
                    timerLabel.Text = $"Tick Count: {ticks}";
                });
            }
        }

        private void SetImage(object? sender, apiEventArgs e)
        {
            MainThread.BeginInvokeOnMainThread(() =>
            {
                mainImage.Source = e.Link;
            });
        }

        private void GetImage(object? sender, EventArgs e)
        {
            if (getRequestThread != null && !getRequestThread.IsAlive)
                getRequestThread = null;

            if (getRequestThread == null)
            {
                getRequestThread = new Thread(new ThreadStart(GetRequest));
                getRequestThread.Start();
            }
        }

        private void GetRequest()
        {
            string apiUrl = "https://random.imagecdn.app/v1/image";

            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = client.GetAsync(apiUrl).Result;

                if (response.IsSuccessStatusCode)
                {
                    string content = response.Content.ReadAsStringAsync().Result;
                    apiService.OnApiResponse(content);
                }
            }
        }
    }
}    
Video
expand arrow
¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 3

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Challenge: Preventing Program Freezes Using Threading

Task Description

Hint
expand arrow

Statements related to UI updates are best to execute in the Main Thread.

Solution
expand arrow
using Microsoft.Maui.Controls.Shapes;
using System.Globalization;
using System.Net.Http;

namespace MauiApp1
{
    public class apiEvent
    {
        public delegate void apiEventHandler(object sender, apiEventArgs e);

        public event apiEventHandler? OnResponse;

        public void OnApiResponse(string content)
        {
            apiEventHandler? handler = OnResponse;

            if (handler != null)
            {
                handler(this, new apiEventArgs(content));
            }
        }
    }

    public class apiEventArgs : EventArgs
    {
        public string Link { get; }

        public apiEventArgs(string content)
        {
            this.Link = content;
        }
    }

    public partial class MainPage : ContentPage
    {
        public apiEvent apiService = new apiEvent();

        Thread? mainTimer;
        Thread? getRequestThread;
        long ticks;

        public MainPage()
        {
            InitializeComponent();

            getImageButton.Clicked += GetImage;
            apiService.OnResponse += SetImage;

            ticks = 0;
            mainTimer = new Thread(new ThreadStart(timerUpdate));
            mainTimer.Start();
        }

        public void timerUpdate()
        {
            while (true)
            {
                ticks++;
                Thread.Sleep(50);
                MainThread.BeginInvokeOnMainThread(() => {
                    timerLabel.Text = $"Tick Count: {ticks}";
                });
            }
        }

        private void SetImage(object? sender, apiEventArgs e)
        {
            MainThread.BeginInvokeOnMainThread(() =>
            {
                mainImage.Source = e.Link;
            });
        }

        private void GetImage(object? sender, EventArgs e)
        {
            if (getRequestThread != null && !getRequestThread.IsAlive)
                getRequestThread = null;

            if (getRequestThread == null)
            {
                getRequestThread = new Thread(new ThreadStart(GetRequest));
                getRequestThread.Start();
            }
        }

        private void GetRequest()
        {
            string apiUrl = "https://random.imagecdn.app/v1/image";

            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = client.GetAsync(apiUrl).Result;

                if (response.IsSuccessStatusCode)
                {
                    string content = response.Content.ReadAsStringAsync().Result;
                    apiService.OnApiResponse(content);
                }
            }
        }
    }
}    
Video
expand arrow
¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 3
some-alt