Thread safety for DataTable

后端 未结 3 1890
孤独总比滥情好
孤独总比滥情好 2020-12-01 11:25

I had read this answer ADO.NET DataTable/DataRow Thread Safety, and can\'t understand some things. Particularly I can\'t understand [2] article. What kind of wrapper I need

3条回答
  •  眼角桃花
    2020-12-01 11:55

    Faced with the same problem, I decided to implement nested ConcurrentDictionaries

    It is generic, but could be changed to use defined types instead. Example method to convert to DataTable included

    /// 
    /// A thread safe data table
    /// 
    /// The X axis type
    /// The Y axis type
    /// The value type
    public class HeatMap
    {
        public ConcurrentDictionary> Table { get; set; } = new ConcurrentDictionary>();
    
        public void SetValue(TX x, TY y, TZ val)
        {
            var row = Table.GetOrAdd(x, u => new ConcurrentDictionary());
    
            row.AddOrUpdate(y, v => val,
                (ty, v) => val);
        }
    
        public TZ GetValue(TX x, TY y)
        {
            var row = Table.GetOrAdd(x, u => new ConcurrentDictionary());
    
            if (!row.TryGetValue(y, out TZ val))
                return default;
    
            return val;
    
        }
    
        public DataTable GetDataTable()
        {
            var dataTable = new DataTable();
    
            dataTable.Columns.Add("");
    
            var columnList = new List();
            foreach (var row in Table)
            {
                foreach (var valueKey in row.Value.Keys)
                {
                    var columnName = valueKey.ToString();
                    if (!columnList.Contains(columnName))
                        columnList.Add(columnName);
                }
            }
    
            foreach (var s in columnList)
                dataTable.Columns.Add(s);
    
            foreach (var row in Table)
            {
                var dataRow = dataTable.NewRow();
                dataRow[0] = row.Key.ToString();
                foreach (var column in row.Value)
                {
                    dataRow[column.Key.ToString()] = column.Value;
                }
    
                dataTable.Rows.Add(dataRow);
            }
    
            return dataTable;
        }
    }
    

提交回复
热议问题