Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Task - Preventing Program Freezes Using Threading | Threading
Advanced C# with .NET

Task - Preventing Program Freezes Using ThreadingTask - Preventing Program Freezes Using Threading

The base program is given on the Github Repository. Clone the repository to begin solving the task.

Task Description

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

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);
                }
            }
        }
    }
}    
      

Все було зрозуміло?

Секція 3. Розділ 3
course content

Зміст курсу

Advanced C# with .NET

Task - Preventing Program Freezes Using ThreadingTask - Preventing Program Freezes Using Threading

The base program is given on the Github Repository. Clone the repository to begin solving the task.

Task Description

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

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);
                }
            }
        }
    }
}    
      

Все було зрозуміло?

Секція 3. Розділ 3
some-alt