Thursday, October 30, 2008

Multithreading and events



Don't you just love Multi-threading, well, I love to see my processor being efficiently used and close to at least 70% utilization. even though threads are dangerous however, using threads carefully will allow your user interface to always be responsive.
Nowthat, we will live with threads, those threads will certainly need to talk to the user interface thread. There are many ways for them to start chit chatting and my prefered way is events.
In this mechanism, a thread will raise an event and anyone who is subscribed to this event will receive the event data and will have a chance to process it.
Here is how to do that.
Let's say you have a calls called "Communicator" which will be processed in a thread and need to raise an event when the thread is done. what you need to do is
1- Define a delegate and an event as follows
//Delegate
public delegate void AlertSentHandler(object sender, SentAlertEventArgs e);
//Event
public event AlertSentHandler AlertSent;
2- Raise the event at the proper time as follows
onAlertSent(this,new SentAlertEventArgs(DateTime.Now.ToString()));
3- Since you are using a helper function called onAlertSent then you need to write it as follows
Protected void onAlertSent(object sender, SentAlertEventArgs e)
{
if (AlertSent != null)
AlertSent(sender, e );
}
The onAlertSent method is checking if the delegate is not null (There are subscribers to the event) and then call the delegate itself as shown above.

Now this event is sent because someone will probably care that the thread is done. those who care that the thread is done should subscribe to the event. To subscribe to this event simply subscribe as follows
cm.AlertSent += new Communicator.AlertSentHandler(cm_AlertSent);
and that is...!!!!!
Note: The above topic is different from serializing the threads (incorrectly called Synchronizing the threads). When you need threads to wait for each others you may want to use the serialization techniques, one of them is the ManualResetEvent
which you may declare like this

static ManualResetEvent threadSerializer = new ManualResetEvent(true );
and make your threads WaitOne like this
threadSerializer.WaitOne();
and set and reset like this
threadSerializer.Reset();
//Do thread work
threadSerializer.Set();
There is a complete and good article about this type of serialization techniques in these links

No comments: