Using these babies, It's much easier to create a delegate and call it from another thread. They are comprised of two classes: UIThreadManager
, and UIThreadHandler
.
UIThreadHandler
is the one doing all the hard work. It works simply by holding a reference to the delegate on the form which you would like to Invoke, and a reference to the Actual form instance. What it saves you is from writing those most common Delegate stubs which would call Invoke on the form.
To do this, it contains a public method called BaseEventHandler
which is overloaded by 6 variations . The most common variations on which Event Handler methods are written. So, it will contain the signature for the EventHandler
Delegate type, and also an Empty signature, single object
, 2 objects
, int
and string
. You can also extend this functionality by either adding overloads or deriving from this class.
UIThreadManager
allows for easy creation of new UIThreadHandler
instances, and holds them in memory using an ArrayList
. Very simple.
Here are three variations on using these classes:
1) I have a long running loop in another thread which throws an EventHandler
type of event. I want to receive this event and call a UI updating method:
//m_uimgr is an instance of UIThreadManager
EventThrower e = new EventThrower();
e.OnEventThrow += m_uimgr.NewHandler(this,new EventHandler(this.UpdateProgressBar));
e.Start();
As you can understand , m_uimgr
creates an instance of a new UIThreadHandler
, loads it with the provided form and delegate, and returns a delegate to one of its stub methods which, when called, calls Invoke()
on the main Form.
2) I have an event other than EventHandler type, Or I have derieved from the UIThreadHandler
and would like to use a different stub method of the new class as a delegate to my thread events.
EventThrower e = new EventThrower();
UIThreadHandler h = m_uimgr.CreateHandler(this,new EventHandler(this.UpdateProgressBar));
e.OnEventThrow += new MyHandlerDelegate(h.BaseEventHandler);
e.Start();
This technique allows you to either add more overloads to the BaseEventHandler
Method, for more flexibility.
3) I have derived from UIThreadHandler and created by own Delegate Handlers
EventThrower e = new EventThrower();
UIThreadHandler h = new UIThreadHandler(this,new MyEventHandler(this.UpdateProgressBar));
m_uimgr.AddHandler(h);
e.OnEventThrow + new MyHandlerDelegate(h.CustomEventHandler);
e.Start();
Comments