Scott Scott - 3 months ago 32
C# Question

Fire timer immediately?

I've reviewed this question, but I'm still having issues. First off, I cannot find a

Timer_Tick
or
.tick
method anywhere. Secondly, if I just call the Elapsed Event Handler manually it isn't on a separate thread and locks the UI.

Here is how my timers are implemented:

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


How can I have
btnQuery1Start
run the query immediately on the System.Timers thread, just as it would after the first interval?

Answer
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());
}

That'll be five cents, please.