using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SunlightCentralizedControlManagement_SCCM_.UserClass
{
///
/// 线程安全的 DataTable 管理器
/// 提供对 DataTable 的安全并发访问
///
public class DataTableManager : IDisposable
{
private DataTable _dataTable;
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
private bool _disposed = false;
#region 构造函数
public DataTableManager()
{
_dataTable = new DataTable();
}
public DataTableManager(DataTable dataTable)
{
_dataTable = dataTable ?? throw new ArgumentNullException(nameof(dataTable));
}
public DataTableManager(string tableName)
{
_dataTable = new DataTable(tableName);
}
#endregion
#region 基本操作
///
/// 安全地添加列
///
public void AddColumn(string columnName, Type dataType)
{
ExecuteWriteOperation(table =>
{
table.Columns.Add(columnName, dataType);
});
}
///
/// 安全地添加行
///
public void AddRow(params object[] values)
{
ExecuteWriteOperation(table =>
{
DataRow newRow = table.NewRow();
for (int i = 0; i < Math.Min(values.Length, table.Columns.Count); i++)
{
newRow[i] = values[i] ?? DBNull.Value;
}
table.Rows.Add(newRow);
});
}
///
/// 安全地更新单元格值
///
public bool UpdateCell(int rowIndex, string columnName, object value)
{
return ExecuteWriteOperation(table =>
{
if (IsValidRowIndex(table, rowIndex) && table.Columns.Contains(columnName))
{
table.Rows[rowIndex][columnName] = value ?? DBNull.Value;
return true;
}
return false;
});
}
///
/// 安全地删除行
///
public bool DeleteRow(int rowIndex)
{
return ExecuteWriteOperation(table =>
{
if (IsValidRowIndex(table, rowIndex))
{
table.Rows[rowIndex].Delete();
return true;
}
return false;
});
}
#endregion
#region 查询操作
///
/// 安全地获取行
///
public DataRow GetRow(int rowIndex)
{
return ExecuteReadOperation(table =>
{
return IsValidRowIndex(table, rowIndex) ? table.Rows[rowIndex] : null;
});
}
///
/// 安全地查找行(使用筛选条件)
///
public DataRow[] FindRows(string filterExpression)
{
return ExecuteReadOperation(table =>
{
try
{
return string.IsNullOrEmpty(filterExpression)
? table.Select()
: table.Select(filterExpression);
}
catch (EvaluateException)
{
return new DataRow[0];
}
});
}
///
/// 安全地获取行数
///
public int GetRowCount()
{
return ExecuteReadOperation(table => table.Rows.Count);
}
///
/// 安全地检查行是否存在
///
public bool RowExists(int rowIndex)
{
return ExecuteReadOperation(table => IsValidRowIndex(table, rowIndex));
}
#endregion
#region 批量操作
///
/// 安全地批量添加行
///
public void BulkAddRows(IEnumerable