如何在.NET 3.5中每2分钟调用一次UserControl中的函数

时间:2014-07-12 04:04:56

标签: c# user-interface

所以我使用dataGridView创建了UserControl,实际上我将如何对这个对象不太重要,但是让我说我​​已经使用了DataSource,我想用这些值刷新dataGridView。

示例我有函数 fillDataGridView(),我希望它每2分钟调用一次

我认为我可以用Thread类做到这一点,但是还没有成功

你如何处理UI刷新?

我知道这看起来像是另一个有UI更新问题的人#34;但是从我看到的我真的可以做到最简单的方法

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
    }
}

它喊出那个

  

类型' System.InvalidOperationException'的例外情况发生在   System.Windows.Forms.dll但未在用户代码中处理   信息:跨线程操作无效:控制' BT_AddTrigger'   从创建它的线程以外的线程访问。

4 个答案:

答案 0 :(得分:5)

使用System.Windows.Forms.Timer代替System.Timer.Timer。

您收到Cross Thread Operation Not Valid错误,因为System.Timer.Timer在另一个线程上运行,并且您无法在不调用Control.Invoke()的情况下从另一个线程调用Winforms线程上的操作。< / p>

System.Windows.Forms.Timer将使用与UI相同的线程,您将避免这些问题。

答案 1 :(得分:2)

您可以使用.Net中的一个方便的Timer类来每2分钟触发一次。

这是一个例子 http://msdn.microsoft.com/en-us/library/system.windows.forms.timer(v=vs.110).aspx

答案 2 :(得分:1)

您可以使用System.Windows.Forms

using System.Windows.Forms;

public Alertbox()
{
    InitializeComponent();

    var timer = new Timer {Interval = 2*60*1000};
    timer.Tick += Timer_Tick;
    timer.Start();
}

void Timer_Tick(object sender, EventArgs e)
{
    BT_AddTrigger.Text += "test";
}

答案 3 :(得分:-1)

您应该以这种方式使用计时器类

            System.Timers.Timer testTimer = new System.Timers.Timer();
            testTimer.Enabled = true;
            //testTimer.Interval = 3600000; //1 hour timer
            testTimer.Interval = 100000;// Execute timer every // five seconds
            testTimer.Elapsed += new System.Timers.ElapsedEventHandler(FillGrid);