Timer and Threading problem

  • Thread starter Thread starter Benny
  • Start date Start date
B

Benny

Hello Experts,

Currently I am working on a windows application using VS.NET 2002 with
C#.

On one of my form, I have a refresh button which will dispose created
controls and re-create them. I need the refresh perform in every certain
period, so I wrote a timer function to perform this:

...
private void InitTimer()
{
timerClock = new System.Timers.Timer();
this.timerClock.Elapsed += new ElapsedEventHandler(OnTimer);
this.timerClock.Interval = 1000 * 60; // every minute
this.timerClock.Enabled = true;
}

private void OnTimer(object sender, ElapsedEventArgs e)
{
try{ Refresh_Click(null, null); }
catch( Exception ex ){ MessageBox.Show(ex.ToString());}
}

Everything working on the timer, it fired up an event (call the OnTimer
function) in every minute.
However, when it execute Refresh_Click(null, null) in the OnTimer
function, it gave me an exception error:

System.ArgumentException: Controls created on one thread cannot be
parented to a
control on a different thread.
at System.Windows.Forms.ControlCollection.Add(Control value)
at System.Windows.Forms.ControlCollection.Add(Control value)
...


The Refresh_Click(object sender, System.EventArgs e) works fine on it
self.

Anyone have any idea why this happened? And how can I solve this
problem?


Thanks,

Benny



*** Sent via Devdex http://www.devdex.com ***
Don't just participate in USENET...get rewarded for it!
 
Why can't you launch it once and use the Timer_Tick event to raise the
necessary actions ?
 
Ken said:
You are trying to dispose/recreate your controls on a thread which is not
the UI thread of the form. To solve this, you have two choices:

1) Use the Timer in System.Windows.Forms namespace by dropping the timer
control on your form.

2) Use the form's Invoke() method from your OnTimer() event handler to
marshal the call to Refresh_Click to the form's UI thread.

BeginInvoke() is generally better if you don't care about synchronous
operation (which you usually don't when you're just handling an event.)

David Logan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Back
Top