首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

WinForms C# 標籤數字累加:用 Random 產生增量而非覆蓋數值

     編輯:程式設計疑難解答

想在 WinForms 應用程式中,讓 Label 每隔一段時間顯示「累計總數」,而不是每次亂數產生一個新數字覆蓋舊值。關鍵在於將累計變數提升為欄位(Field),並在 Timer 或背景執行緒中只做「total += 隨機增量」再更新 UI。

錯誤寫法(每次重新產生隨機數)

private void timer_Tick(object sender, EventArgs e)
{
    Random ran = new Random();           // 每次新建種子相近,品質差
    var sd = ran.Next(20, 300);          // 區域變數,離開方法即銷毀
    lblWait.Text = sd + " 個";           // 直接顯示隨機值,非累加
}

正確寫法(欄位累加 + 單一 Random 實例)

public partial class MainForm : Form
{
    private int totalCount = 0;          // 1. 欄位保存累計值
    private readonly Random rand = new Random(); // 2. 單一 Random 實例

    public MainForm()
    {
        InitializeComponent();
        timer.Interval = 1000;           // 1 秒觸發一次
        timer.Tick += Timer_Tick;
        timer.Start();
    }

    private void Timer_Tick(object sender, EventArgs e)
    {
        int increment = rand.Next(20, 300); // 產生增量
        totalCount += increment;             // 3. 累加
        lblWait.Text = $"{totalCount} 個";   // 4. 更新 UI
    }
}

進階:跨執行緒安全更新 UI

若在 Task.Run 或 BackgroundWorker 計算,更新 Label 必須回主執行緒:

private async void StartBtn_Click(object sender, EventArgs e)
{
    await Task.Run(() =>
    {
        for (int i = 0; i < 100; i++)
        {
            int inc = rand.Next(20, 300);
            totalCount += inc;
            this.Invoke((Action)(() => lblWait.Text = $"{totalCount} 個"));
            Thread.Sleep(1000);
        }
    });
}

關鍵點總結

  1. 累計變數宣告為類別欄位,生命週期等同視窗實例。
  2. Random 實例只建一次,避免短時間多次 new Random() 產生相同序列。
  3. 每次只 產生增量並累加,而非重新產生總值。
  4. 跨執行緒更新 UI 用 Control.Invoke 或 async/await + Progress<T>。

套用這個模式,不管是倒數計時、統計點擊、模擬感測器資料,都能讓 Label 平滑顯示「只增不減」的累計數字。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved