"Bill McCormick" <wp*********@gmail.comwrote in message
news:Iz*****************@newssvr14.news.prodigy.ne t...
A timer control (I think) runs in another thread apart from a main form.
In the OnTick event, you can update some form control with no worries.
I'm making an AsyncronousServer class that runs in a separate thread and
I'd like to have server generated events (OnListen, OnConnect, OnSend,
OnRecieve, and so on) update a form control.
The only way I can figure out how to do this is to check InvokeRequired
and use Invoke on the form control from the event handler.
Is this the best way to do this? How does the timer control do this?
I haven't used the timer control, but if it truly runs on a different thread
then it does have to do Invoke or BeginInvoke to run code on the main UI
thread. (If the timer control actually just uses WM_TIMER messages, then it
doesn't really run on a different thread per se, as the OS is handling the
timing issues for you, and the issue goes away).
And yes, you need to also use Invoke or BeginInvoke to do the same.
Personally, I remain unconvinced that there's any good reason to use
InvokeRequired. I prefer to have the invoking method different from the
method that actually does the work anyway, and breaking the recursion of
Invoking the same method that does the Invoke is the only real benefit of
using InvokeRequired (and so isn't necessary when two different methods are
used).
For example:
private void _CrossThreadSetText(string strNew)
{
Invoke(new SetTextDelegate(_SetText), new object[] { strNew });
}
private void _SetText(string strNew)
{
label1.Text = strNew;
}
In the above example, all callers could use _CrossThreadSetText, or you
could limit its use to just other threads, letting callers you know are
running on the main thread call _SetText directly. Either will work fine,
and there's no need to call InvokeRequired.
Frankly, I find the convention used everywhere in the MSDN documentation of
having a re-entrant invoking method to be very awkward.
Pete