Question

I am fairly new to programming so any help will be taken on board, I am trying to get my CreateTable to run every 2 seconds however when I click my button to execute InitLoop nothing happens, I have tried various different things but haven't been able to get this to work successfully.

    private void CreateTable()
    {            
        //Set the number of columns and rows
        int tblColumns = 20;
        int tblRows = 50;
        //Create the table
        Table tbl = new Table();

        tbl.CssClass = "table";
        //Add table
        PlaceHolder1.Controls.Add(tbl);
        Random RandomNumber = new Random();
        for (int i = 0; i < tblRows; i++)
        {
            TableRow tr = new TableRow();
            for (int j = 0; j < tblColumns; j++)
            {
                TableCell tc = new TableCell();
                int Range = RandomNumber.Next(1, 99);
                tc.Text = Range.ToString();
                //Add Columns
                tr.Cells.Add(tc);
            }
            //Add Rows
            tbl.Rows.Add(tr);
        }
        return;
    }

    System.Timers.Timer myTimer = new System.Timers.Timer();

    private void InitLoop(bool runLoop)
    {
        while (true)
        {
            try
            {
                myTimer.Elapsed += myTimer_Elapsed;
                myTimer.Interval = 2000;
                myTimer.Enabled = true;
                myTimer.Start();
            }
            catch (Exception f)
            {
                //handle the exception 
            }
        }
    }

    private void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        CreateTable();
    }
Was it helpful?

Solution

The timer is all you need. The infinite loop is rapidly resetting the timer, so nothing happens.

private void InitLoop(bool runLoop)
{
    try
    {
        myTimer.Elapsed += myTimer_Elapsed;
        myTimer.Interval = 2000;
        myTimer.Enabled = true;
        myTimer.Start();
    }
    catch (Exception f)
    {
        //handle the exception 
    }
}

typically you don't want an infinite loop without some kind of a thread.sleep() command, because it will also drive the CPU to 100% trying to run the loop as fast as possible.

OTHER TIPS

The callbacks occur, but most likely the method CreateTable throws an exception. The reason for the exception is that the method tries to change a gui object. In order to change such an object you must be on the gui thread. The thing you need to look up is Dispatcher, and how to dispatch callbacks.

Verify by adding a try-catch to the timer callback method and debug, or write the exception to log file or similar.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top