-1

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?

Community
  • 1
  • 1

1 Answers1

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

That'll be five cents, please.

  • 1
    I'm new to .net, can you explain why moving the code to a `protected void` allows it to run on a thread like the timer does? –  Sep 07 '16 at 17:14
  • Could I not just do `Task.Run(() => doQuery1(null,null)` with the same result? –  Sep 07 '16 at 17:16
  • 1
    @Scott You could, but somebody would come along later and waste time figuring out what those nulls meant. Only use event handler methods for event handers. Method that does stuff with no parameters should be `MethodThatDoesStuff()`. – 15ee8f99-57ff-4f92-890c-b56153 Sep 07 '16 at 17:18
  • Makes sense. Thanks –  Sep 07 '16 at 17:18
  • 1
    @Scott You're missing a using, unless you're on a lower version of .NET, in which case you need to use `System.Threading.Thread`. – 15ee8f99-57ff-4f92-890c-b56153 Sep 07 '16 at 17:18