Safe Threading in C#

Simple explanation. Its a bit like recursion….

Identify the class thats being called from another thread – lets assume its got a few Windows Form calls in it.  

I’ll use the example here.  I have a multithreaded application and one of the worker threads needs to update a text box – on the main app screen.

The class is within the main GUI form  – mainform.cs and ist defined as:

private void MessageHandler_Message(int nId, string sMessage)

The idea behnid this is to marshall into the original thread that contains the GUI code. You need to declare a callback function – like this within the main class.

delegate void MessageHandler_MessageCallback(int id, string sMessage);

OK, so its got the same arguments.

Now in the class thats being called – 

MessageHandler_Message(int nId, string sMessage) it needs re-writing to be thread aware.

private void MessageHandler_Message(int nId, string sMessage){

// Check to see if we are in the correct thread

if (this.InvokeRequired){ // We need to create the callback function in the corrrect thread

MessageHandler_MessageCallback m = new MessageHandler_MessageCallback(MessageHandler_Message);

// Callback function is in the right thread – .Invoke fires it there.this.Invoke(m, new object[] { nId, sMessage }); }else{// If we get here we must be in the right thread


int nItem = m_listBoxMessages.Items.Add(string.Format(“({0}) <{1}> {2}”, nId, System.DateTime.Now, sMessage));if (m_listBoxMessages.Items.Count > 5000){m_listBoxMessages.Items.RemoveAt(0);

if (m_listBoxMessages.SelectedIndex < 0){ {m_listBoxMessages.TopIndex = nItem;}

else if (m_listBoxMessages.SelectedIndex == nItem – 1){m_listBoxMessages.SelectedIndex = nItem;