Why not use multicast delegates and cross-thread invoke:
void CrossThreadInvokeSingle(Delegate delegate, Args args)
{
Control ctl = delegate.Target as Control;
if (ctl != null)
ctl.Invoke(delegate, args);
else
delegate.DynamicInvoke(args);
}
void CrossThreadInvokeMulti(MultiCastDelegate delegate, Args args)
{
foreach (Delegate item in delegate.GetInvocationList())
{
CrossThreadInvokeSingle(item, args);
}
}
Delegate, MultiCastDelegate are part of CRL.
Args stands for any arguments you may wish to pass to delegate call.
In this case you can subscribe to the event in your form and any number of child controls and call without penalty
and explicit knowledge of what is being called. E.g.
class MyForm : Form
{
void UpdateControls() {
DoUpdate();
}
MyForm() {
OtherThreadObject.OnFinish += new MyDelegate(UpdateControls);
}
}
class OtherThreadClass {
public event MyDelegate OnFinish;
private void InvokeOnFinish() {
if (OnFinish != null)
CrossThreadInvokeMulti(OnFinish);
}
}
OtherThreadClass does not know about form or any subscriber, the only limitation that thread-tied handlers should
be declared in control descendants.
This works great when you have single UI thread with any number of workers.
Tom wrote:
Hi Everybody
I want to update some controls in a form from another threads. I did it by passing the form to that thread and calling a delegate with Form1.Invoke, I want to have just one delegeate for all of my controls in the Form and dont define one delegate for each control. Some thing like to have a switch case in that delegate fucntion and passing control name to it...
what is the impact of this method in comparison with Form1.TreeView1.Invoke(...)
Thanks,
Tom