You can only update the GUI from the main thread.
In your working method (calculate ()), you are trying to add items to the list.
lbPrimes.Items.Add(currval.ToString());
This throws an exception.
You gain access to a control that is not thread safe. When a thread that has not created a control tries to call it, you will get an InvalidOperationException.
If you want to add items to the list, you need to use InvokeRequired, as stated in TheCodeKing.
For instance:
private delegate void AddListItem(string item); private void AddListBoxItem(string item) { if (this.lbPrimes.InvokeRequired) { AddListItem d = new AddListItem(item); this.Invoke(d, new object[] { item}); } else { this.lbPrimes.Items.Add(item); } }
Call this AddListBoxItem (...) method in your Calculate () method instead of directly trying to add items to the list control.
source share