解决DataGridView在多线程中滚动条卡死的问题
如果在子线程中使用了代码去刷新DataGridView的数据,可能会出现滚动条卡死的问题,具体解决方法如下:
方法1:
将子线程关于DataGridView操作的这部分代码放回主线程,在子线程中去操作DataGridView时,很容易导致DataGridView右侧滚动条卡死。
方法2:
使用委托来解决,即将关于DataGridView的这部分代码放进委托里面,DataGridView的操作仍然在子线程里面。
this.Invoke(new Action(delegate{
//绑定datagridview代码
}));
以下是示例代码:
private void GetSysInfo()
{
this.Invoke(new Action(delegate
{
//绑定datagridview代码
int i = 0;
try
{
this.dgvSystem.Rows.Clear();
dList = Collect.Configuration.getInstance().DeviceList;
htCollector = ThreadManager.GetInstance().HtCollector;
foreach (string key in dList.Keys)
{
DeviceInfo deviceInfo = dList[key];
i = dgvSystem.Rows.Add();
dgvSystem.Rows[i].Cells["colSystem"].Value = deviceInfo.GetSubSystemName();
//dgvSystem.Rows[i].Cells["colInsideCode"].Value = deviceInfo.Protocol;
if (null == htCollector || 0 == htCollector.Count)
{
//dgvSystem.Rows[i].Cells["colstatus"].Value = "NoStart";
dgvSystem.Rows[i].Cells["colStarttime"].Value = "";
dgvSystem.Rows[i].Cells["colDataTime"].Value = "";
}
else
{
ClientInfo ci = ((Collector)htCollector[key]).clientInfo;
//dgvSystem.Rows[i].Cells["colstatus"].Value = ci.SysStatus;
dgvSystem.Rows[i].Cells["colStarttime"].Value = ci.StartTime.ToString();
dgvSystem.Rows[i].Cells["colDataTime"].Value = ci.LastDataTime.ToString();
}
this.dgvSystem.FirstDisplayedScrollingRowIndex = i;
}
dgvSystem.Refresh();
//开启定时器,去定时刷新系统信息
tmSysInfo = new System.Timers.Timer(1000);
tmSysInfo.Elapsed += new ElapsedEventHandler(RefreshSysInfo);
tmSysInfo.AutoReset = true;
tmSysInfo.Enabled = true;
tmSysInfo.Start();
//dgvSystem.ColumnHeadersDefaultCellStyle.ForeColor = Color.Red;
}
catch (Exception e)
{
log.Error("FrmMain ", "GetSysInfo Error: " + e.Message);
}
}));
return;
}