想在 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 + " 個"; // 直接顯示隨機值,非累加
}
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
}
}
若在 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);
}
});
}
new Random() 產生相同序列。Control.Invoke 或 async/await + Progress<T>。套用這個模式,不管是倒數計時、統計點擊、模擬感測器資料,都能讓 Label 平滑顯示「只增不減」的累計數字。