C# WINDOWS MAUI專案 (c# maui task thread ui example)

C# WINDOWS MAUI專案 (c# maui task thread ui example)

C# WINDOWS MAUI專案 (c# maui task thread ui example)


資料來源:chatGPT


chatGPT Code:

using Microsoft.Maui.Controls;
using System;
using System.Threading.Tasks;
using System.Threading;

public class MainPage : ContentPage
{
    private Label resultLabel;

    public MainPage()
    {
        resultLabel = new Label
        {
            Text = "計算中...",
            HorizontalOptions = LayoutOptions.CenterAndExpand,
            VerticalOptions = LayoutOptions.CenterAndExpand
        };

        var calculateButton = new Button
        {
            Text = "開始計算",
            HorizontalOptions = LayoutOptions.CenterAndExpand
        };

        calculateButton.Clicked += async (sender, args) =>
        {
            resultLabel.Text = "計算中...";
            
            // 使用 Task.Run 在後台執行計算
            await Task.Run(() =>
            {
                int result = Calculate();
                // 使用 Device.BeginInvokeOnMainThread 更新 UI
                Device.BeginInvokeOnMainThread(() =>
                {
                    resultLabel.Text = $"計算結果: {result}";
                });
            });
        };

        Content = new StackLayout
        {
            Children = { resultLabel, calculateButton },
            VerticalOptions = LayoutOptions.CenterAndExpand,
            HorizontalOptions = LayoutOptions.CenterAndExpand
        };
    }

    private int Calculate()
    {
        // 模擬耗時計算
        Thread.Sleep(5000);
        return 42;
    }
}

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *