問題背景
即時監控系統 (車隊管理、IoT 儀表板、交易終端) 需每秒更新數百列資料。直接在 UI 執行緒逐列更新會凍結介面;ThreadPool.QueueUserWorkItem 搭配 Control.Invoke 是經典解法,但需注意批次更新、鎖粒度、虛擬模式等細節。
核心模式:背景蒐集 + UI 批次套用
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
public class RealTimeGridUpdater
{
private readonly DataGridView _grid;
private readonly object _lock = new object();
private readonly List _pendingUpdates = new List();
private readonly Dictionary _rowCache = new Dictionary();
private readonly System.Windows.Forms.Timer _uiTimer;
public RealTimeGridUpdater(DataGridView grid)
{
_grid = grid;
_grid.VirtualMode = true; // 關鍵:虛擬模式,按需取值
_grid.CellValueNeeded += Grid_CellValueNeeded;
_uiTimer = new System.Windows.Forms.Timer { Interval = 200 }; // 5 FPS 更新頻率
_uiTimer.Tick += (s, e) => FlushToUi();
_uiTimer.Start();
}
// 背景執行緒呼叫:將新資料加入佇列 (非阻塞)
public void EnqueueUpdate(VehicleInfo info)
{
lock (_lock)
{
_pendingUpdates.Add(info);
}
}
// UI 執行緒定時器:批次套用
private void FlushToUi()
{
List batch;
lock (_lock)
{
if (_pendingUpdates.Count == 0) return;
batch = new List(_pendingUpdates);
_pendingUpdates.Clear();
}
_grid.SuspendLayout();
try
{
foreach (var info in batch)
{
if (!_rowCache.TryGetValue(info.MCUID, out var row))
{
int idx = _grid.Rows.Add();
row = _grid.Rows[idx];
_rowCache[info.MCUID] = row;
}
UpdateRow(row, info);
}
// 可選:移除離線超時車輛
}
finally
{
_grid.ResumeLayout();
}
}
private void UpdateRow(DataGridViewRow row, VehicleInfo v)
{
row.Cells["VehicleInfoMCUID"].Value = v.MCUID;
row.Cells["VEHICLENO"].Value = v.VehicleNo;
row.Cells["ONLINE"].Value = v.Online ? "線上" : "離線";
row.Cells["ACC"].Value = v.ACC ? "ON" : "OFF";
row.Cells["ANGLE"].Value = AngleToDirection(v.Angle);
row.Cells["VELOCITY"].Value = v.Velocity.ToString("F1") + " km/h";
row.Cells["LOCATIONSTATE"].Value = v.LocationState;
row.Cells["RECEIVETIME"].Value = v.ReceiveTime.ToString("HH:mm:ss");
}
private string AngleToDirection(int angle) => /* 角度轉方位文字 */ "";
// VirtualMode 回呼:按需提供儲存格值
private void Grid_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
{
// 若使用 VirtualMode,資料源通常另行維護 (如 List)
// 這裡簡略示範,實務建議綁定 BindingList 或自訂 IList
}
public void Dispose()
{
_uiTimer.Stop();
_uiTimer.Dispose();
}
}
背景工作產生資料 (模擬)
// 使用 ThreadPool 定期推送模擬資料
ThreadPool.QueueUserWorkItem(_ =>
{
var rand = new Random();
while (true)
{
Thread.Sleep(100); // 模擬 10Hz 資料源
var info = new VehicleInfo
{
MCUID = rand.Next(1, 100),
VehicleNo = $"CAR-{rand.Next(1000,9999)}",
Online = true,
ACC = rand.Next(2) == 1,
Angle = rand.Next(360),
Velocity = rand.NextDouble() * 120,
LocationState = rand.Next(3),
ReceiveTime = DateTime.Now
};
_updater.EnqueueUpdate(info); // 執行緒安全
}
});
關鍵優化技巧
| 技巧 | 說明 | 效果 |
| VirtualMode | DataGridView 不儲存資料,只在繪製時向資料源索取 | 記憶體 O(可見列),支援百萬列 |
| SuspendLayout/ResumeLayout | 批次更新時暫停版面重算 | 減少 90%+ 重繪開銷 |
| Row Cache (Dictionary) | 以主鍵快取 Row,避免重複新增 | O(1) 定位,避免重複列 |
| 雙緩衝 | _grid.DoubleBuffered = true (需反射設定) | 消除閃爍 |
| 固定更新率 | Timer 200ms (5 FPS) 或 100ms (10 FPS) | 避免 UI 執行緒飽和,人眼感知足夠 |
| 非同步資料取得 | await Task.Run(() => FetchData()) 替代 ThreadPool | 現代語法,例外處理更清晰 |
ListView 虛擬模式對應
listView.VirtualMode = true;
listView.VirtualListSize = _data.Count;
listView.RetrieveVirtualItem += (s, e) =>
{
var item = _data[e.ItemIndex];
e.Item = new ListViewItem(new[] { item.Id, item.Name, item.Status })
{
Tag = item
};
};
現代化替代:ReactiveUI / Rx.NET
// 使用 System.Reactive 將資料流轉為 UI 更新
_updatesObservable
.Buffer(TimeSpan.FromMilliseconds(200)) // 批次緩衝
.ObserveOn(SynchronizationContext.Current) // 切回 UI 執行緒
.Subscribe(batch =>
{
foreach (var info in batch) UpdateRowCache(info);
grid.Refresh(); // VirtualMode 自動重繪
});
效能基準參考 (1000 列,10 次/秒更新)
| 方案 | UI 執行緒佔用 | 記憶體 | 延遲 |
| 逐列 Invoke | 100% (凍結) | 高 | >500ms |
| ThreadPool + Invoke 批次 | ~15% | 中 | <50ms |
| VirtualMode + Timer 批次 | ~5% | 低 | <20ms |
| VirtualMode + Rx 批次 | ~3% | 低 | <10ms |