Need help understanding threads....
Posted on 2006-07-03
Here's the problem....
I need to have 4 worker threads and a main thread. Each of the worker threads continually moniter a COM port for input. Any time they get input, they add that input to a list and notify the main thread that something has been added to the list. The main thread should then look at the list and see what was added.
How do I do this? I've looked at several examples, but none of them seem to cover this particular issue.
The rest of the post is what I've tried. I keep getting errors about controls only being accessable by the thread that created them. I *thought* the purpose of raising an event was so that threads could communicate. What am I doing wrong?
public class StringListWithEvents : List<string>
public delegate void ListAddEventHandler();
public event ListAddEventHandler ListAdded;
public virtual void OnListAdd()
if (ListAdded != null)
public class MainForm
protected ThreadStart myThreadStart;
protected Thread myThread;
public StringListWithEvents myList = new StringListWithEvents();
public void InitializeComponent()
private System.Windows.Forms.ListBox myListBox;
myListBox = new System.Windows.Forms.ListBox();
m_strlstIDCard.ListAdded += new StringListWithEvents.ListAddEventHandler(ItemAdded);
myThreadStart = new ThreadStart(MyThreadStuff)
myThread = new Thread(myThreadStart);
public void ItemAdded()
foreach (string a in myList)
myListBox.Items.Add(a); //this is where it bombs with the error