0

I have a windows form application. I am supposed a create an SQL job, and execute it. The SQL job consists of around 9 steps and takes around 4 hours to complete. I am supposed to display the status of the SQL job, in a datagridview, so that its not necessary to go to SQL server and monitor the events.

My code is as below

 public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {


            Thread t1 = new Thread(FirstThread);
            t1.Start();
            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = 500;
            timer.Enabled = true;

            timer.Elapsed += timer1_Tick;
            timer.Start();
            t1.Join();


        }
 private void FirstThread()
        {

            // Creates a job
            // Invoke the job, via a bat file

        }
 private void checkStatus()
        {            
            // Checks the status of the job using the EXEC sp_helpjob @jobName='JobName'
            // Populate the status on the DataGridView
            // If the status of the job, eg. 
            dataGridView1.DataSource = ds.Tables[0];
            int CurrentExecution = Convert.ToInt32(dt.Rows[0]["Current_Execution_Status"]);
            if (CurrentExecution == 4)
                label1.Text = "Job is Over";
        }

        private void timer1_Tick(object sender, EventArgs e)
        {

            checkStatus();
        }

I run into CrossThread Operation Not valid error. Could anyone please let me know how to call the UI controls inside the System.Timer Thread.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
cmrhema
  • 981
  • 2
  • 16
  • 28

1 Answers1

3

You should call Invoke on the Control or Form:

this.Invoke((MethodInvoker)delegate() { label1.Text = "Job is Over"; });

Or BeginInvoke if you don't want to wait until the action ended:

this.BeginInvoke((MethodInvoker)delegate() { label1.Text = "Job is Over"; });
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325