You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将ConcurrentDictionary各Key对应List末尾OHLC绑定到DataGridView无需每次重绑定

最优绑定方案实现思路

核心逻辑

你不需要每次重建BindingList并重绑数据源,只需要初始化一次绑定关系,后续仅维护绑定集合内的元素即可,依赖OHLC已经实现的INotifyPropertyChanged接口自动同步属性变更,仅需要在K线实体替换(如新K线生成)时更新绑定集合的对应元素,配合UI刷新节流实现高效更新。

具体实现步骤

1. 定义成员变量

// 原有K线存储字典
ConcurrentDictionary<string, List<OHLC>> candles = new ConcurrentDictionary<string, List<OHLC>>();
// 绑定用集合,全局仅初始化一次,永不更换引用
BindingList<OHLC> LastCandles = new BindingList<OHLC>();
// 股票代码到最新K线实体的映射,用于快速查找更新
ConcurrentDictionary<string, OHLC> symbolToLastCandleMap = new ConcurrentDictionary<string, OHLC>();
// 刷新节流标记
private bool _isRefreshPending = false;
// 节流间隔,可根据需求调整,单位毫秒
private const int RefreshThrottleMs = 100;

默认BindingList的RaiseListChangedEvents为true,集合元素增删、元素属性变更时会自动通知UI更新,节流刷新仅用于高频更新场景下降低重绘频率。

2. 初始化绑定(仅执行一次)

在窗体初始化逻辑中执行一次绑定,后续永远不需要重新赋值DataSource:

form1.dataGridView1.DataSource = LastCandles;

3. 实现增量更新逻辑

如果可以拿到本次更新的股票代码,仅处理对应股票即可,不需要全量遍历字典:

public void OnUpdate(string updatedSymbol)
{
    // 你的原有K线更新逻辑
    // ...

    // 仅处理本次更新的股票
    if (candles.TryGetValue(updatedSymbol, out var klineList) && klineList.Count > 0)
    {
        var latestCandle = klineList.Last();
        // 封送UI操作到UI线程执行
        form1.dataGridView1.BeginInvoke((MethodInvoker)delegate 
        {
            if (symbolToLastCandleMap.TryGetValue(updatedSymbol, out var existingLastCandle))
            {
                if (existingLastCandle != latestCandle)
                {
                    // 新K线生成,替换绑定集合中的旧实体
                    LastCandles.Remove(existingLastCandle);
                    LastCandles.Add(latestCandle);
                    symbolToLastCandleMap[updatedSymbol] = latestCandle;
                }
                // 否则是现有K线属性更新,依赖INotifyPropertyChanged自动同步,无需操作集合
            }
            else
            {
                // 新增股票,加入绑定集合
                LastCandles.Add(latestCandle);
                symbolToLastCandleMap.TryAdd(updatedSymbol, latestCandle);
            }

            // 节流触发UI刷新
            if (!_isRefreshPending)
            {
                _isRefreshPending = true;
                Task.Delay(RefreshThrottleMs).ContinueWith(_ => 
                {
                    form1.dataGridView1.BeginInvoke((MethodInvoker)delegate 
                    {
                        form1.dataGridView1.Refresh();
                        _isRefreshPending = false;
                    });
                });
            }
        });
    }
}

如果无法获取到本次更新的股票代码,可以遍历candles的所有Key做批量处理,性能也远高于重建集合重绑。

进阶自动同步方案(可选)

如果希望完全不需要手动调用更新逻辑,可以将每个股票的List<OHLC>替换为ObservableCollection<OHLC>,订阅每个集合的CollectionChanged事件,当集合新增元素时自动触发对应最新K线的更新,完全解耦业务更新逻辑和UI绑定逻辑。

内容的提问来源于stack exchange,提问作者user2146441

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:06:00