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

Challenge: Preventing Program Freezes Using Threading

Stryg for at vise menuen

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
Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 3. Kapitel 3

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Sektion 3. Kapitel 3
some-alt