所以我用dataGridView创建了UserControl,实际上我将如何对这个对象不太重要,但是假设我已经使用了DataSource,我想用这些值刷新dataGridView.
例如,我有函数fillDataGridView(),我希望它每2分钟调用一次
我认为我可以用Thread类做到这一点,但还没有成功
你如何处理UI刷新?
我知道这看起来像"另一个有UI更新问题的人",但从我看到的我真的不能用最简单的方法来做到这一点
public partial class Alertbox : UserControl
{
private static System.Timers.Timer aTimer;
public Alertbox()
{
InitializeComponent();
aTimer = new System.Timers.Timer(10000);
aTimer.Elapsed += new ElapsedEventHandler(Update);
aTimer.Interval = 2000;
aTimer.Enabled = true;
}
public void Update(object source, ElapsedEventArgs e)
{
BT_AddTrigger.Text += "test"; // append to button text
}
}
Run Code Online (Sandbox Code Playgroud)
它喊出来了
System.Windows.Forms.dll中发生类型为"System.InvalidOperationException"的异常但未在用户代码中处理附加信息:跨线程操作无效:控制从其创建的线程以外的线程访问的"BT_AddTrigger"上.
使用System.Windows.Forms.Timer而不是System.Timer.Timer.
您收到Cross Thread Operation Not Valid错误是因为System.Timer.Timer在另一个线程上运行,并且您无法在不调用Control.Invoke()的情况下从另一个线程调用Winforms线程上的操作.
System.Windows.Forms.Timer将使用与UI相同的线程,您将避免这些问题.
| 归档时间: |
|
| 查看次数: |
773 次 |
| 最近记录: |