火灾计时器立即?

时间:2016-09-07 17:11:52

标签: c# timer

我已经审核了this question,但我仍然遇到问题。首先,我无法在任何地方找到Timer_Tick.tick方法。其次,如果我只是手动调用Elapsed Event Handler,它就不在单独的线程上并锁定UI。

以下是我的计时器的实施方式:

public partial class Form1 : Form
{
    System.Timers.Timer query1Timer = new System.Timers.Timer();
    ...

    private void Form1_Load(object sender, EventArgs e)
    {
        query1Timer.Elapsed += new ElapsedEventHandler(doQuery1);
        ...

    public void doQuery1(object source, ElapsedEventArgs e)
    {
        //long running ODBC query
    }

    private void btnQuery1Start_Click(object sender, EventArgs e)
    {
        query1Timer.Interval = Convert.ToInt32(txtQuery1Interval.Text) * 1000;
        query1Timer.Enabled = true;
    }

如何让btnQuery1Start立即在System.Timers线程上运行查询,就像在第一个间隔之后一样?

1 个答案:

答案 0 :(得分:3)

protected void PerformLongRunningODBCQuery()
{
    // ...long running ODBC query stuff. 
}

public void doQuery1(object source, ElapsedEventArgs e)
{
    PerformLongRunningODBCQuery();
}

private void btnQuery1Start_Click(object sender, EventArgs e)
{
    query1Timer.Interval = Convert.ToInt32(txtQuery1Interval.Text) * 1000;
    query1Timer.Enabled = true;
    Task.Run(() => PerformLongRunningODBCQuery());
}

请给我五美分。