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

Challenge: Preventing Program Freezes Using Threading

Veeg om het menu te tonen

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
Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 3. Hoofdstuk 3

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

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
Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 3. Hoofdstuk 3
some-alt